Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Stop Coroutine while its running?

Discussion in 'Scripting' started by Terraya, Oct 8, 2020.

  1. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646
    Hey there,

    i have a Coroutine which i store in a variable as it used to be:

    Code (CSharp):
    1. IEnumerator storedCoroutine
    and well, the function for example is something like this:

    Code (CSharp):
    1.  
    2. aiMover.Agent.SetDestination(interactableMovePoints.movePoint.transform.position);
    3.  
    4. yield return new WaitUntil(() => !aiMover.Agent.pathPending);
    5. yield return new WaitUntil(() => aiMover.ReturnDistanceToTarget() <= 0.2);
    6.  
    7. aiMover.StopNavMesh();
    8. yield return new WaitForSeconds(0.4f);
    9. SetupAnimator(aiMover.Anim);
    10.  
    so the problem here is, even if i stop the coroutine,
    he still runs the whole thing until it finishes .. ,
    which means, if the AI is still running towards a place,
    he still goes there and sets up the animator ... even i stop the coroutine before,

    so in total: Is there any way to Stop a Coroutine even its not completed?


    EDIT: PLEASE READ

    - The problem here is not that he ends up running till the end, becouse that will get stopped,
    but the problem is that he will setup the Animation when he reaches the end .. , so in case my AI wants to sit.. it does stop but then it runs the "Sit" animation in the last function
     
    Last edited: Oct 8, 2020
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,697
    How are you stopping the coroutine?

    You should be doing it like this:
    Code (CSharp):
    1. // Start
    2. storedCoroutine = StartCoroutine(MyCoroutine());
    3.  
    4. // Stop
    5. StopCoroutine(storedCoroutine);
     
    Terraya likes this.
  3. Terraya

    Terraya

    Joined:
    Mar 8, 2018
    Posts:
    646

    Yes well, i got a InputReader which Stops the Function by Running:

    Code (CSharp):
    1. StopCoroutine(storedCoroutine);
    but that still didnt help,

    i just figured it out .. my fault since i didnt watch the docs before ...
    https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html

    at the bottom you see that the "running" coroutine also needs to get stored
    in a variable as this:

    Code (CSharp):
    1. Coroutine runningCoroutine = StartCoroutine(storedCoroutine);
    by this you can actualy cancel it while its running by:

    Code (CSharp):
    1. StopCoroutine(runningCoroutine );
     
    filip-bencin likes this.