Setting an object as Active/Inactive only works intermittently.

I have a script that will set a light to active/inactive depending on the and play a “click” noise. However, the active/inactive state will only change every so often, seemingly randomly. The click however will work without fail, which means my input is being detected. The relevant code:

void OnTriggerStay(Collider col) { if(col.gameObject.tag == "Player") { if(Input.GetKeyDown(KeyCode.Mouse0)) { lightSources.SetActive(!lightSources.activeSelf); clickSound.Play(); } } }

Does anyone have any thoughts on this?

Hello @Stevificus,

Huh. I would suggest that you move the Input.GetKeyDown out of OnTriggerStay() into Update() because OnTriggerStay() runs on the physics update loop while GetKeyDown registers on the frame update loop, but… you say you’re hearing the click.

I’m going to suggest you try this anyway and use a boolean to “link” the collision to allowing the keypress instead of putting the keypress inside the if() statement within OnTriggerStay(). What might be happening is that the physics loop is causing GetKeyDown to register twice when a frame changes in the midst of a physics update, and you don’t see the switch because it’s happening too fast. You would still hear the sound in this scenario, so this is my strongest hypothesis.

Let me know if you need help with the code to make this work. (link for more explanation: Unity - Scripting API: Collider.OnTriggerStay(Collider))