- Home /
 
How to stop a single variant of a Coroutine?
I'm making a Coroutine helper class that would handle everything related to Coroutine. In that helper, I have a switch where 3 cases would start the same IEnumerator. I've seen that you can store the return of StartCoroutine but my problem is that, even though it's the same IEnumerator, their attributes are different from each other. To give an example, imagine I need to change a color of something using Coroutine. I would create a single IEnumerator where I would pass the color. Then for example I started a IEnumerator for yellow, red, and green. What if I wanted to stop red? 
 I tried the suggestion of @andrew-lukasik but have to make some changes to make it "work". Like using List instead of a Dictionary. I ended up using a List of a struct that contains a ScriptableObject and a IEnumerator. My problem now is that StopCoroutine(IEnumerator); doesn't stop the IEnumerator for some reason. 
You should use Switch Case for whole staues.I guess like this
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 public class DuoBehaviour : $$anonymous$$onoBehaviour
 {
     Dictionary<string,IEnumerator> _routines = new Dictionary<string,IEnumerator>(10);
     public Coroutine StartCoroutineWithID ( IEnumerator routine , string id )
     {
         var coroutine = StartCoroutine( routine );
         if( !_routines.ContainsKey(id) ) _routines.Add( id , routine );
         else
         {
             StopCoroutine( _routines[id] );
             _routines[id] = routine;
         }
         return coroutine;
     }
     public void StopCoroutineWithID ( string id )
     {
         if( _routines.TryGetValue(id,out var routine) )
         {
             StopCoroutine( routine );
             _routines.Remove( id );
         }
         else Debug.LogWarning($"coroutine '{id}' not found");
     }
 }
 
                   StartCoroutineWithID( $$anonymous$$akeSomething(Color.red) , "make it red" );
 StartCoroutineWithID( $$anonymous$$akeSomething(Color.green) , "make it green" );
 // milliseconds later...
 StopCoroutineWithID( "make it red" );
 
                 seems like this would work. will try it
Answer by Bunny83 · Jul 27, 2020 at 04:43 PM
Each coroutine or IEnumerator instance is a seperate unique object in memory. There is no way to distinguish them. So if you want to stop a certain coroutine, you have to remember the object you've created. Either the IEnumerator or the corresponding Coroutine object.
Maybe reading through my coroutine explaination which I wrote recently might help to better understand how they actually work.
Can't really say that I need all that information right now, but it would be really useful in the future. Thanks
Your answer