- Home /
Creating custom input actions
I'm trying to create a sort of "interact" key that when pressed by the player, would check to see if an object is interactable and if so, call the object's attached "interact" method.
The key itself is what I'm having trouble with. I assumed this would be relatively simple, but apparently key binding is not as simple as I thought. I created the following simple script:
using UnityEngine;
using System.Collections;
public class Interact : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey("E")) {
Debug.Log ("Attempting to Interact");
}
}
}
I attached the script to the first person controller and assumed if they pressed the 'E' key, this would print to the console but it's not.
What would be required to sort of bind a new key to have it's own custom function like this?
Answer by AlucardJay · Nov 12, 2012 at 05:14 AM
http://docs.unity3d.com/Documentation/ScriptReference/Input.GetKey.html
for using a string as an input, it needs to be lowercase :
if ( Input.GetKey("e") )
for using keycode :
if ( Input.GetKey(KeyCode.E) )
http://docs.unity3d.com/Documentation/ScriptReference/KeyCode.html
I personally got into the habit of using keycode, for the personal reason of string searches generally take longer.
More info on Input : http://docs.unity3d.com/Documentation/ScriptReference/Input.html
NOTE - You may also want to use Get$$anonymous$$eyDown or Get$$anonymous$$eyUp, as these will only fire ONCE per key press.
$$anonymous$$eyGey will return 'true' every single frame that the key is down, so only use it if you want to continually run your functions.