- Home /
Reset a coroutine on event
Hello everyone,
I'm struggling with a coroutine. I'm using it to make a random timer when enemy is attacking my player. If nothing else is happening, it's running just as I want. Here is the code :
randomWait = Random.Range(2, 4); //It generates a random number
yield return new WaitForSeconds(randomWait); //Enemy waits the returned number
animator.SetTrigger("Push"); //Then it attacks.
But, I'm trying to reset it when enemy is taking a hit. I tried with if/else, with a yield return null
but enemy behaviour is quite random. Sometimes I'm attacking him, enemy falls, gets up and is attacking while I'm not at range of its attacks. It looks like I'm attacking him just before "Push" is triggered, and when its "hurt" animation is over, it resumes coroutine.
How to completely stop that coroutine, cancel any instruction and make it ready for next start ? I alos tried with stopcoroutine(mycoroutine)
but no results so far...
Thanks
You could use something like this if(randomWait < Time.time || enemyIsHurt){return null;}
where the enemyIsHurt
is a bool you use to know when it is available to attack, also in your Random.Range(2, 4)
change them to floats, at the moment you are returning ints so your range is limited to second increments
I tried with your code, but now enemy can't attack. What is the meaning of randomWait < Time.time
?
waitUntill/randomWait = Time.time + Random.Range(2, 4);
Like that so it sets a ranom time either 2 or 3 seconds from when you set it, Hense why I said about using floats
so that it can be between the range not just the second increments.
Answer by Neferlem · May 06, 2019 at 08:30 PM
I tried with another method : I created a function that launches at the end of enemy animation. My goal was to avoid enemy making an attack when It finishes its invulnerability frames. So I made a marker at the end of animation, that launches a StopCoroutine(myCoroutine);
At first StopCoroutine was cancelling coroutine without giving it possibility to restart, now it properly restart. Using some debug.log, I could check when coroutine launched, stopped and restarted. Thanks @fafase and @Bciam for your kind help