Eduard Hasanaj Eduard Hasanaj - 3 months ago 23
C# Question

Unity coroutine not work as expected

Hello friends< i am having hard time with unity coroutines. Let"s say I start a coroutine. When I stop should the code below yield be executed0? I THINK NO.
AM I WRONG? here is my code

[PunRPC]
public void timerstart(){
StopCoroutine(time ());
currentplayerbar.fillAmount=1.0f;
currentplayerbar=timebar[turn-1];
StartCoroutine(time());
Debug.Log("time started");
}

IEnumerator time(){
Debug.Log("start coroutine");
timer=60;
timerisruning=true;
yield return new WaitForSeconds(60);

Debug.Log("60 sec passed");
timerisruning=false;
if(id==turn){
if (passnumber==3){
//StartCoroutine (noplayeractivity ());

}

else {


passnumber++;
turn+=1;
Hashtable turnbupdate=new Hashtable (){{"turn",turn},{"pass",passnumber}};
PhotonNetwork.room.SetCustomProperties(turnbupdate);
photonView.RPC("timerstart",PhotonTargets.All);
PhotonNetwork.SendOutgoingCommands();
}
}




}


In debugger I see four debug logs Debug.Log("60 sec passed"); withpout any
Debug.Log("start coroutine"); beetwen. I think that they are runing in paralel but why? I stopped coroutine before started new one

Answer

When you call StopCoroutine(time ()); you're not stopping the previously started coroutine. You're creating a new coroutine, without starting it and ending it in the same line.

You can fix it in two ways:

  1. Call them not by reference but reflection - simply put, change the calls to:

    StopCoroutine("time");
    ...
    StartCoroutine("time");
    
  2. Store the running coroutine in a variable

    var coroutine:IEnumerator;
    
    [PunRPC]
    public void timerstart(){
        if(coroutine != null)
          StopCoroutine(coroutine);
        ...
        coroutine=time();
        StartCoroutine(coroutine);
    }
    
Comments