Wait OnTriggerEnter2D in IEnumerator
Hi guys, I got the bug about trigger collider.
public bool hasCollision = false;
int temp = 5;
IEnumerator StartGo()
{
temp--;
if (temp == 0 && !hasCollision)
{
// do stuff A
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(!hasCollision)
{
if (collision.tag.Equals("rabit"))
{
hasCollision = true;
// do stuff B
}
}
}
But sometime, the IEnumerator run before OnTriggerEnter2D() finished. It means that sometime it executes stuff A then B
How to resolve this?
Answer by Okido · May 13, 2018 at 11:40 AM
This is with the assumption that you want to execute stuff A when the rabbit hits the trigger, wait 5 seconds, then execute stuff B - if I'm wrong do provide more info (:
the way you're counting down with temp isn't in seconds so it would reach zero in just a few frames. If you mean to do it in seconds, you can just use
yield return new WaitForSeconds(temp);
The way it's written now it looks like stuff A would only work until the collision with the rabbit occurs, because you set the collision to true, but stuff B can only be called while collision is false. Also there's no reference to StartGo here so there's no way to tell when you're calling it.
If you want the IEnumerator to run after the trigger is hit, you should call in within the trigger text and change the hasCollision condition to true in your if statement. If you use WaitForSeconds instead you don't need to check the temp value either.
Your answer
Follow this Question
Related Questions
Change Scene with Physics Raycasting 1 Answer
C# Activate Object on Collision with tag not working. 1 Answer
Help with Trigger Colliders.. 0 Answers
Trigger enter and directly Exit 0 Answers
ANIMATION TRIGGER DOESN'T PLAY 1 Answer