Unity协程不能按预期工作

时间:2015-10-19 20:21:18

标签: c# unity3d coroutine

你好朋友<我很难与团结协同作战。让我们说我开始了一个协程。当我停止时,下面的代码应该执行0?我想不是。 我错了吗?这是我的代码

[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();
        }
    }




}

在调试器中,我看到四个调试日志Debug.Log("传递60秒"); withpout any Debug.Log("启动协同程序"); beetwen。我认为他们正在参加比赛,但为什么呢?在开始新的

之前我停止了coroutine

1 个答案:

答案 0 :(得分:0)

当您致电StopCoroutine(time ());时,您并未停止之前启动的协程。您正在创建一个新的协同程序,而无需启动它并在同一行中结束它。

您可以通过两种方式解决问题:

  1. 不是通过引用而是反射来调用它们 - 只需将调用更改为:

    StopCoroutine("time");
    ...
    StartCoroutine("time");
    
  2. 将正在运行的协同程序存储在变量

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