【问题标题】:Unity coroutine not work as expectedUnity协程无法按预期工作
【发布时间】:2015-10-19 20:21:18
【问题描述】:

你好朋友

[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 sec pass");没有任何 Debug.Log("启动协程");贝特温。我认为它们是并行运行的,但为什么呢?我在开始新的协程之前停止了协程

【问题讨论】:

  • 这是这个问题的错误地方。由于您的问题是关于 Unity 游戏引擎的,因此您应该使用“Unity3d”标签。
  • 我做到了。看得更清楚
  • 如果您误解了我的意思:您使用了“Unity”标签,这是一种不同的技术,而不是 Unity 引擎。我告诉你这个,以防你将来可能会问更多关于 Unity 引擎的问题,在这种情况下,“Unity3d”标签是合适的。
  • 好吧对不起我的错误

标签: c# unity3d coroutine


【解决方案1】:

当您调用StopCoroutine(time ()); 时,您并没有停止之前启动的协程。你正在创建一个新的协程,而不是在同一行开始和结束它。

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

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

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

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

【讨论】:

    猜你喜欢
    • 2018-02-02
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    • 2022-08-07
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 2014-12-09
    相关资源
    最近更新 更多