document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.Events;
  4. using System.Collections;
  5.  
  6. [System.Serializable]
  7. public class KeyBinding : MonoBehaviour {
  8.  
  9.     //Name comes from enum in KeyBindingsManager scrip
  10.     public keyType keyName;
  11.     //keycode set in inspector and by player
  12.     public KeyCode thisKey = KeyCode.W;
  13.     //Text to display keycode for user feedback
  14.     public Text keyDisplay;
  15.  
  16.     //Used for color changing during key binding
  17.     public GameObject button;
  18.     public Color toggleColor = new Color();
  19.     Image buttonImage;
  20.     Color originalColor;
  21.  
  22.     //Internal variables
  23.     bool reassignKey = false;
  24.     Event curEvent;
  25.  
  26.     //Changes in button behavior should be made here
  27.     void OnGUI()
  28.     {
  29.         curEvent = Event.current;
  30.         //Checks if key is pressed and if button has been pressed indicating wanting to re-assign
  31.         if(curEvent.isKey && curEvent.keyCode != KeyCode.None && reassignKey)
  32.         {
  33.             thisKey = curEvent.keyCode;
  34.             ChangeKeyCode();
  35.             UpdateKeyCode();
  36.             SaveKeyCode();
  37.         }
  38.     }
  39.  
  40.     //Initializes
  41.     void Awake()
  42.     {
  43.         buttonImage = button.GetComponent<Image>();
  44.         originalColor = buttonImage.color;
  45.         button.GetComponent<Button>().onClick.AddListener(() => ChangeKeyCode());
  46.     }
  47.  
  48.     //Loads keycodes from player preferences
  49.     void OnEnable()
  50.     {
  51.         KeyCode tempKey;
  52.         tempKey = (KeyCode) PlayerPrefs.GetInt(keyName.ToString());
  53.         if(tempKey.ToString() == "None")
  54.         {
  55.             Debug.Log("Got No Key Code");
  56.         }
  57.         else
  58.         {
  59.             thisKey = tempKey;
  60.             keyDisplay.text = thisKey.ToString();
  61.             UpdateKeyCode();
  62.         }
  63.     }
  64.  
  65.     //Called by button on GUI
  66.     public void ChangeKeyCode()
  67.     {
  68.         reassignKey = !reassignKey;
  69.  
  70.         if(reassignKey)
  71.             buttonImage.color = toggleColor;
  72.         else
  73.             buttonImage.color = originalColor;
  74.     }
  75.        
  76.     //saves keycode to player prefs
  77.     public void SaveKeyCode()
  78.     {
  79.         keyDisplay.text = thisKey.ToString();
  80.         PlayerPrefs.SetInt(keyName.ToString(),(int)thisKey);
  81.         PlayerPrefs.Save();
  82.     }
  83.  
  84.     //updates dictionary on key bindings manager
  85.     void UpdateKeyCode()
  86.     {      
  87.         KeyBindingManager.singleton.UpdateDictionary(keyName,thisKey);
  88.     }
  89. }
');