Multiple StartCoroutine Call

Hello,

Let me be honest, the question isn’t complete because I don’t know the proper term for a field which refer to an IEnumerable returning function. At the beginning, I simply want to ensure whenever I have to stop the referenced coroutine before starting a new one. But, my test give bizarre result.

Here’s my testing code:

public class MultiStartCoroutineTest : MonoBehaviour
{
    private IEnumerator CounterHandler;
    private WaitForSeconds WaitForOneSecond;

    private void Start()
    {
        CounterHandler = Counter();
        WaitForOneSecond = new WaitForSeconds(1);
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
            StartCoroutine(CounterHandler);
    }

    private IEnumerator Counter()
    {
        Debug.Log("Counter is started");

        int i = 0;
        while(true)
        {
            yield return WaitForOneSecond;
            Debug.Log(++i);
        }
    }
}

Here’s all my hypothesis:

→ If Unity doesn’t allow multi startcoroutine of referenced ‘IEnumerator’, then “Counter is started” will be printed once and the counter will still increment per second.
→ If Unity allow multi StartCoroutine of referenced IEnumerator, then Counter is started will be printed multiple times (per coroutine start) and there will be multi counter printed (with different counting step).

Result:

When I repeatedly press spacebar,

Counter is started only printed once during the first spacebar pressed, as if Unity doesn’t allow ‘parallel’ coroutine.
→ Counter increment become faster every time spacebar is pressed, as if there are ‘parallel’ coroutines which SHARE the same i variable.

This make me baffled, especially the ‘variable sharing’ part.

Could someone please explain why or tell my what documentation I should read? Thanks in advance! :slight_smile:

P.S. I’m bad with correct term in programming, I hope you guys understand my question…

P.S.2 I’ve made sure I turned off ‘collapse’ in console window.

I believe you are essentially saving the state of your coroutine through multiple calls to it when you saved your IEnumberable/WaitForSeconds to a class variable.

If you want unrelated parallel coroutine calls, you can simply call them:

 //You can remove this section
 private IEnumerator CounterHandler;
 private WaitForSeconds WaitForOneSecond;

 private void Start()
 {
     CounterHandler = Counter();
     WaitForOneSecond = new WaitForSeconds(1);
 }

 //Create a new timer for each instance
 yield return new WaitForSeconds(1);

 //And make sure you call the coroutine instead
StartCoroutine("Counter");