hamel123 hamel123 - 13 days ago 6
C# Question

Object inactive by pressing a button

I'm facing a problem in

unity3d
when active and disabling an object. I want to enable the object when i press a key,and disable on press it again. I think my code is fine. But it's doesn't working correctly on unity editor when i press the button first time object is activated,than immediately inactive 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