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…


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