IEnumerator Stalling Or Stopping

Hi Community!

[Question Solved: See answer comments for demonstrated solution]

I’m truly stumped by this issue. When I supply my IEnumerator yield’s WaitForSeconds parameter with 0.1f-0.9f, it works fine. However, when I supply it with an int from another script, hangs up on the WaitForSeconds bit, and just doesn’t move past that line of code. I have Debugged and found that it is getting an int (1) as a parameter. Interestingly, if I hard-code the value of 1 into the WaitForSeconds parameter, it does the same thing.

Here’s my code:

    public IEnumerator Slow(int projLevel) //Accept the level of the projectile as parameter
    {
        if (slowed) yield break; //If we're already slowed, break out
        slowed = true; //Let the script know we're slowed
        enemy.speed /= projLevel+1; //Slow down this enemy
        yield return new WaitForSeconds(projLevel); //Wait for supplied time (this is where it stops)
        enemy.speed *= projLevel+1; //Speed up our enemy to normal speed
        slowed = false; //Let the script know we're no longer slowed
    }

A coroutine stops when the MonoBehaviour that calls StartCoroutine is destroyed. So if your call to StartCoroutine comes from the bullet script, you will stop the coroutine running on the other object when the bullet is destroyed.

Solve this by calling StartCoroutine on the target Component. Either by implementing a wrapper method, or by calling someOtherMonobehaviour.StartCoroutine().

To emphasise: It does not matter where the IEnumerator is located. It matters where StartCoroutine is called.

Are you sure you start the coroutine on the enemy and not the bullet which might get destroyed the next moment? It doesn’t depend where the IEnumerator method is defined. It only matters which StartCoroutine method you used to start the coroutine. StartCoroutine is a method of the MonoBehaviour class. The coroutine runs on the MonoBehaviour instance on which you use StartCoroutine.

So without more details about your actual setup we can’t help you any further.

@Runalotski @Rostam24:
The data type “int” can be implicitly converted to “float”, so that’s not a problem here.