hamel123 hamel123 - 13 days ago 6
C# Question

Key press with Input.GetKey returns true multiple times

I'm facing a problem in

unity3d
when activating and de-activating an object. I want to enable the object when I press a key, and disable it when I press it again.

I think my code is fine. But it's doesn't working correctly. When I press the button first time, object is activated, then immediately deactivates sometimes key press work fine sometimes not. I think it's because of
Update()
function, it runs on every frame.I don't know what I do.

Code:

public class A : MonoBehaviour
{
[SerializeField]
private GameObject invSystem;
[SerializeField]
bool buttonCheck;

void Update()
{
if (Input.GetKey(KeyCode.P))
{

if (!buttonCheck)
{
invSystem.SetActive(true);
buttonCheck = true;
}

else
{
invSystem.SetActive(false);
buttonCheck = false;
}
}
}
}

Answer

Use GetKeyDown which will only be true only once in a frame until relased and pressed again. GetKey whill return true while it is held down. This will make it to be triggered more than once making your if statement to be true and executed multiple times in a frame.

if (Input.GetKey (KeyCode.P)) should be replaced with if (Input.GetKeyDown(KeyCode.P))

Comments