Search code examples
unity-game-enginerestartcoroutine

Unity 5.0.1 Completely Stopping a Coroutine


Alright so I am running into a slight issue, basically, I have a Coroutine that contains a for-loop. I can call the StopCoroutine and StartCoroutine methods successfully, but of course, that just pauses and unpauses the Coroutine. Is there a way to actually stop it and restart it? My end-goal here is to be able to start a Coroutine, kill it at the user's discretion, and restart it from the beginning any time, also at the user's discretion. Is this accomplishable? Thanks.


Solution

  • To "rewind" the coroutine, just call the coroutine method again with the same parameters. If you want to save these parameters, you can use closures:

    public class CoroutineClosureExample : MonoBehaviour
    {
        private System.Func<IEnumerator> CreateCoroutineFactory(int someInt, float someFloat)
        {
            return () => CoroutineYouWant(someInt, someFloat);
        }
    
        private IEnumerator CoroutineYouWant(int someInt, float someFloat)
        {
            for(int i = 0; i < someInt; i++)
            {
                yield return new WaitForEndOfFrame();
            }
        }
    
        private System.Func<IEnumerator> m_CurrentCoroutineFactory;
        private IEnumerator m_CurrentCoroutine;
    
        public void SetCoroutineParameters(int someInt, float someFloat)
        {
            m_CurrentCoroutineFactory = CreateCoroutineFactory(someInt, someFloat);
        }
    
        public void RestartCurrentCoroutine()
        {
            if (m_CurrentCoroutine != null)
            {
                StopCoroutine(m_CurrentCoroutine);
                m_CurrentCoroutine = null;
            }
            if (m_CurrentCoroutineFactory != null)
            {
                m_CurrentCoroutine = m_CurrentCoroutineFactory();
                StartCoroutine(m_CurrentCoroutine);
            }
        }
    }