Coroutine start and stop

Hello human beings!

I want to have a coroutine which moves an object but i also want to be able to stop the coroutine in the middle and start it from the beginning or restart it at any way…

What i have now:

public IEnumerator walkCoroutine;
    void Start () {
    		walkCoroutine = WalkingCoroutine ();
		StartCoroutine (walkCoroutine);
    	}
    ...
    
   if (Input.GetKeyDown (KeyCode.H)) {
			StopCoroutine (walkCoroutine);
			print ("STOPED");
		}
		if(Input.GetKeyDown(KeyCode.J)){
			walkCoroutine = WalkingCoroutine ();
			StartCoroutine (walkCoroutine);
			print ("STARTED");
		}
    
...
    
   IEnumerator WalkingCoroutine(){
		iTween.MoveTo (gameObject, iTween.Hash (
			"path", walkingPath,
			"time", timeToWalk,
			"easetype", "linear",
			"looktarget", rotationIndicator,
			"looktime", 0.1f,
			"axis", "y", 
			"onupdate", "CheckIfOnNode", 
			"onComplete", "FinishPath"));
		
		yield return null;
	}

Please help me since it’s very important for my project.

Ethan

Since you’re already using iTween there’s absolutely no need to be touching Coroutines. Just use iTween’s Pause and Resume functions like so:

void Start () {
    iTween.MoveTo (gameObject, iTween.Hash (
         "path", walkingPath,
         "time", timeToWalk,
         "easetype", "linear",
         "looktarget", rotationIndicator,
         "looktime", 0.1f,
         "axis", "y", 
         "onupdate", "CheckIfOnNode", 
         "onComplete", "FinishPath"));
}
     ...
     
    if (Input.GetKeyDown (KeyCode.H)) {
             iTween.Pause(gameObject, "MoveTo");
             print ("STOPED");
         }
         if(Input.GetKeyDown(KeyCode.J)){
             iTween.Resume(gameObject, "MoveTo");
             print ("STARTED");
         }
 ...

Use the Couroutine reference that is returned by StartCoroutine:

EDIT: After your edit of the question I see your problem. The solution stopping a coroutine of course only works if there actually is a loop in it that performs work :slight_smile:

Coroutine walkingPath = null;

void Start () {
        walkingPath  =  StartCoroutine ("WalkingPath");
     }
 ...
 
 if (Input.GetKeyDown (KeyCode.H) && walkingPath  != null) {
             StopCoroutine (walkingPath );
         }
         if(Input.GetKeyDown(KeyCode.J) && walkingPath  == null){
             walkingPath  = StartCoroutine ("WalkingPath");
         }
 
 ...
 
 IEnumerator WalkingPath(){

         while(true){
              //Some code to move
              yield return null;
          }
     }