C# Unity协同程序未按预期工作

C# Unity协同程序未按预期工作,c#,unity3d,coroutine,C#,Unity3d,Coroutine,你好,朋友们。

你好,朋友们。<我在unity Corroutines的日子不好过。假设我启动了一个协同程序。当我停止时,下面的代码应该被执行吗。 我错了吗?这是我的密码

[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秒通过”);其中包含任何
Debug.Log(“start coroutine”);beetwen。我认为它们是并行运行的,但为什么呢?当您调用
StopCoroutine(time());
时,我在启动新的协同程序之前停止了协同程序。

您没有停止以前启动的协同程序。您正在创建一个新的协同程序,而没有在同一行中启动和结束它

您可以通过两种方式修复它:

  • 不是通过引用而是通过反射调用它们-简单地说,将调用更改为:

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

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

  • 这个问题的位置不对。因为你的问题是关于Unity游戏引擎的,所以你应该使用“Unity3d”标签。我这样做了。如果你误解了我,请参见betterIn:你使用了“Unity”“标签,这是一个不同的技术,而不是统一的引擎。我告诉你这一点,以防你将来可能会问更多关于Unity引擎的问题,在这种情况下,“Unity3d”标签是合适的。好的,很抱歉我的错误