- Home /
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!
Answer by Jack-Mariani · May 28, 2019 at 07:21 AM
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
...
}
}
}
Answer by Darioszka · May 28, 2019 at 07:34 AM
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
}
Answer by cs120319992 · May 28, 2019 at 01:52 PM
List<GameObject> enteredTriggers = new List<GameObject>();
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);
}
}
Answer by Eco-Editor · Jun 02, 2019 at 11:35 AM
Hello @cs120319992 The approach seems correct but I cannot enter the for loop. Also I've added the [i] to the count of the gameobjects:
List<GameObject> enteredTriggers = new List<GameObject>();
private void OnTriggerEnter2D(Collider2D col) {
for(int i = 0; i < enteredTriggers.Count; i++) {
if(col.gameObject == enteredTriggers[i]) {
// second time entered
return;
}
// if not entered
// blablabla
enteredTriggers.Add(col.gameObject);
}
}
$$anonymous$$y fix:
if (other.gameObject.CompareTag("Gate"))
{
if (enteredTriggers.Contains(other.gameObject))
{
//Do something
return;
}
else
{
enteredTriggers.Add(other.gameObject);
//and do somethign as well
}
}