How to check if player is re-entering the same trigger?

Good day everybody!

I have a question about the correct logic for the next trigger:

In case A (image below):

The trigger in the scene is enabling light each time the player enters the trigger. There’re several triggers and they all do the same - enable light when OnTriggerEnter() is called.

In case B:

This is a bug that I have: the trigger enables light each time the player enters the trigger, BUT when the player decides to go back and re-enter the same trigger the NEXT light would be enabled and I don’t want that.

The light is enabled by order. Each time a method is called the NEXT light is enabled. Very fast I get “index out of range” error.

How can I tell the script to only execute the function once if the the same trigger has been re-entered?

Thank you!

You can use a bool to check if the trigger was already activated.

Like this:

public class TriggerOnce : MonoBehaviour
{
    private bool _triggeredAlready = false;

    private void OnTriggerEnter(Collider other)
    {
        //ignore if already triggered
        if(_triggeredAlready) return;
        //check if the other is the player, with a tag or as you prefer
        if (other.gameObject.CompareTag("Player"))
        {
            //confirm the trigger
            _triggeredAlready = true;
            //do your logic
            ...
        }
    }
}

I would check the bool variable. Unless it’s not enough in your project.

private bool isLightOn = false;
 private void OnTriggerEnter2D(Collider2D other)
{
       if (isLightOn)
        {
            return;
        }
isLightOn = true;

 //enable light
}

List enteredTriggers = new List();

private void OnTriggerEnter2D(Collider2D col) {
for(int i = 0; i < enteredTriggers.Count; i++) {
if(col.gameObject == enteredTriggers) {
// second time entered
return;
}

// if not entered 
// blablabla
enteredTriggers.Add(col.gameObject);
}
}

Hello @cs120319992
The approach seems correct but I cannot enter the for loop.
Also I’ve added the to the count of the gameobjects:

List enteredTriggers = new List();

private void OnTriggerEnter2D(Collider2D col) {
for(int i = 0; i < enteredTriggers.Count; i++) {
if(col.gameObject == enteredTriggers*) {*
// second time entered
return;
}

// if not entered
// blablabla
enteredTriggers.Add(col.gameObject);
}
}