Input.GetKeyDown not working
Hi, I'm trying to get an input from the "space" button, but it looks like it doesn't take the input when I click. Here's my code:
else if (other.gameObject.tag == "RedDoor") {
if (redKey_canvas.enabled) {
print("entered the door with the key");
if (Input.GetKeyDown(KeyCode.Space)) {
print("Space clicked!);
//OPEN DOOR
other.gameObject.GetComponent<SpriteRenderer>().sprite = enterDoor;
redKey_canvas.enabled = false;
}
}
In the console, I get the "entered door with key" message, but when I press Space, nothing happens.
I've also tried to add an Axis to the Input Manager named "DoorEnter", but it doesn't work either...
Are you calling this in an update function? If yes in which one? Because Input doesn't get reliably registered in FixedUpdate for example. You notice some key events aren't registered at all.
Also untill which point do these debug messages get printed? Do you really have an object with the tag "RedDoor"? $$anonymous$$aybe you're checking the tag on the collider which might have a different tag than it's parent if you put the collider in a child object.
Answer by Balgy · Dec 24, 2016 at 11:39 PM
Input.GetKeyDown needs to be called from the Update() function since the state gets reset each frame. It will not return true until the user has released the key and pressed it again.
If you already have it in the Update() function, then try
Input.GetKeyDown("space")
Instead of
Input.GetKeyDown(KeyCode.Space)
seems to have solved my problem.
Surprisingly, five years after, this is still the thing to be done - at least when building for mobile... so what's the point of having KeyCode?
Answer by tanoshimi · Dec 24, 2016 at 07:40 PM
What function is this code contained in? I'm guessing it's something like OnTriggerEnter? That fires in a single frame in which you enter a trigger. And Input.GetKeyDown also fires in only a single frame in which you press a key. So, do you really press the space bar key and enter the trigger at exactly the same 1/60th of a second?
Answer by knightOfSecrets · Aug 21, 2019 at 01:19 PM
make sure that after running the game at unity u click by the mouse on the game scene (i.e. make sure the game scene is selected)
Thank you this worked . lol sometimes why you have the scene and game view side by side , issues like this pop up.