'if' check inside an OnTriggerStay is called numerous times although it shouldn't? (DRIVING ME INSANE)

I remember helping someone who had a similar problem, but I can’t seem to help myself.

I don’t know what the heck, but I just have a trigger box collider, when the player steps in it and presses ‘e’ - I toggle on/off an item box (Similar to Resident Evil 1,2,3,0)

private void OnTriggerStay(Collider other)
{
	if (other.tag == Tags.player)
	{
		if (Input.GetKeyDown(KeyCode.E))
		{
			StartCoroutine(ToggleBag());
			cnt++;
			Debug.Log("WTF??! " + cnt + " FROM " + this); // I get like, 18 for the first time I press 'e', 37 for the 2nd, etc
		}
	}
}

private IEnumerator ToggleBag() // If I don't do this, Unity barks: "destroying gameobjects immediately is not permitted" 
{
	yield return new WaitForEndOfFrame();
	itemBox.rootPanel.gameObject.SetActive(!itemBox.rootPanel.gameObject.activeSelf);
}

And YES, I could use some boolean hacks, like:

void OnTriggerEnter(Collider other)
{
   if (other.gameObject.tag == Tags.player)
      isInside = true;
}

void OnTriggerExit(Collider other)
{
   if (other.gameObject.tag == Tags.player)
      isInside = false;
}

void Update()
{
    if (isInside && Input.GetKeyDown(KeyCode.E))
      StartCoroutine(ToggleBag());
{

I’m not looking for hacks, I’m looking for an explanation as to why the check body is being executed more than once because it shouldn’t, as Input.GetKeyDown returns true only in the frame the key is pressed in, and then it becomes false, so… does this mean it’s getting executed more than once IN ONE FRAME??

And yes, I’ve tried Input.GetKeyUp – didn’t make a difference.

Any idea?

Thanks a bunch.

GetKeyDown method should be used only in the Update() method. See the doc.

OnTriggerStay is also called at every frame, but I don’t really know when, compared to the Update method. So the “hack” you proposed yourself is quite exactly what you should do :slight_smile: