- Home /
Input.GetKey(KeyCode.E) Not Working
I have a situation where when the player collides with a tree it has the option to select "E" and wood will be added to the inventory. This is my script:
void OnTriggerEnter (Collider other)
{
if (other.tag == "Tree")
{
Debug.Log ("hit");
if(Input.GetKey(KeyCode.E))
{
AddItem (2);
Debug.Log ("wood added");
}
}
}
The first debug, "hit" responds but the second does not. The AddItem (2) command works because I inserted before (Input.GetKey(KeyCode.E)). What am I doing wrong? Is Input.GetKey(KeyCode.E) incorrect?
Thanks in advanced
I believe Input.Get$$anonymous$$ey* can only be used in Update
"Note also that the Input flags are not reset until "Update()", so its suggested you make all the Input Calls in the Update Loop."
@perchik is right. From the Input Reference
"Note also that the Input flags are not reset until "Update()", so its suggested you make all the Input Calls in the Update Loop."
https://docs.unity3d.com/Documentation/ScriptReference/Input.html
I am doing the same thing. How would I enter a door by clicking or pressing a button when I am close if I don't put it in OnTriggerEnter?
Ideally, you would still want a trigger region to handle OnTriggerEnter. Then, while you're in that region, you can open the door with a button press.
// C#
bool inRange = false;
// Walk up to the door
void OnTriggerEnter(Collider other)
{
if(other.CompareTag("Player"))
{
inRange = true;
}
}
// Walk away from the door
void OnTriggerExit(Collider other)
{
if(other.CompareTag("Player"))
{
inRange = false;
}
}
void Update()
{
if(inRange && Input.Get$$anonymous$$eyDown($$anonymous$$eycode.E))
{
// Open door here
}
}
Answer by Leuthil · Mar 26, 2014 at 07:48 PM
To perchik's comment, you will want to set a boolean which says when a tree was hit within that frame from OnTriggerEnter.
private bool treeHit = false;
void OnTriggerEnter (Collider other)
{
if (other.tag == "Tree")
{
Debug.Log ("hit");
treeHit = true;
}
}
void Update()
{
if (treeHit && Input.GetKey(KeyCode.E))
{
Debug.Log("wood added");
treeHit = false;
}
}