Search Unity

StopCoroutine works strange..

Discussion in 'Scripting' started by AbgaryanFX, Mar 4, 2015.

  1. AbgaryanFX

    AbgaryanFX

    Joined:
    Jan 9, 2010
    Posts:
    167
    Hello !

    Strange thing happening with coroutine when I'm calling it for second time.
    It's like StartCoroutine continuing execution...not starting over.
    First I'm calling StartCoroutine, then StopCoroutine (in the mid of execution).
    After that i'm calling StartCoroutine for Second time - expecting that code should do "Debug.Log("Routine - Started");", but it DOESN'T,
    Execution continues from "Debug.Log("Routine - Time is up");" command.
    The result is on picture. Code is in spoiler.

    What's wrong with this code ?



    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class PGate : MonoBehaviour
    6. {
    7.     private IEnumerator routine;
    8.     private Action close;
    9.  
    10.     void Awake()
    11.     {
    12.         routine = WaitAndDo(10f, () => { });
    13.     }
    14.  
    15.     void ButtonDown(int internalID)
    16.     {
    17.         // Start Counting
    18.         Debug.Log("Start");
    19.         StartCoroutine(routine);
    20.     }
    21.  
    22.     void ButtonUp(int internalID)
    23.     {
    24.         // Stop
    25.         Debug.Log("Stop");
    26.         StopCoroutine(routine);
    27.     }
    28.  
    29.     IEnumerator WaitAndDo(float time, Action a)
    30.     {
    31.         Debug.Log("Routine - Started");
    32.         yield return new WaitForSeconds(time);
    33.         Debug.Log("Routine - Time is up");
    34.         if (a == null) Debug.Log("Action is null.");
    35.         else
    36.         {
    37.             Debug.Log("Call");
    38.             a();
    39.         }
    40.     }
    41. }
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Because you're passing the same IEnumerator (routine) around.
     
  3. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    Yeah, I think that's intended behavior, even though it doesn't seem to specifically say it in the docs. Stopping then restarting the same instance of an IEnumerator coroutine is like pausing then resuming it where it left off. If you want to start a new instance of the coroutine, you should move "routine = WaitAndDo(10f, ()=>{});" into ButtonDown.
     
    AbgaryanFX likes this.
  4. AbgaryanFX

    AbgaryanFX

    Joined:
    Jan 9, 2010
    Posts:
    167
    thanks for making things clear ! I think your solution for me is the best and only ;)
    Reset is the correct way, but it doesn't work (not implemented :))
    routine.Reset();


    Thanks for replies !