簡體   English   中英

如果 StartCoroutine 在游戲啟動時啟動,則它僅適用於 1 個以上的對象

[英]StartCoroutine only works for more than 1 object if it starts when the game launch

我試圖為 5 個對象應用相同的協程,當協程在游戲開始時開始時,5 個對象執行該協程,但是當我讓它們通過其他類開始時,只有 1 個對象啟動協程。

這是使 5 個對象啟動協程的代碼:

public class NpcMoveRandomly : MonoBehaviour
{
    NavMeshAgent navMeshAgent;
    public float timeForNewPath;
    public bool inCoroutine;
    Vector3 target;

    void Start()
    {
        navMeshAgent = GetComponent<NavMeshAgent>();
    }

    void Update()
    {
        if (!inCoroutine)
        {
            StartCoroutine(MoveRandomly());
        }
    }

    Vector3 getNewRandomPosition()
    {
        float x = Random.Range(-5, 5);
        float z = Random.Range(-5, 5);

        Vector3 pos = new Vector3(x, 0 ,z);
        return pos;
    }

    public IEnumerator MoveRandomly()
    {       
        inCoroutine = true;
        yield return new WaitForSeconds(timeForNewPath);
        GetNewPath();
        inCoroutine = false;

    }

    void GetNewPath()
    {
        target = getNewRandomPosition();
        navMeshAgent.SetDestination(target);
    }
}

現在只有 1 個對象啟動協程的代碼(我將僅展示差異):

//public bool inCoroutine; I changed the inCourotine to startCoroutine but the rest of the code is basicly the same
public bool startCoroutine;

void Update()
{
    if (startCoroutine)
    {
        StartCoroutine(MoveRandomly());
    }
}

public IEnumerator MoveRandomly()
{
    startCoroutine = false;
    ...
    ...
    startCoroutine = true;

}

在其他班級:

public NpcMoveRandomly npcMoveRandomly;

public void Method()
{
    npcMoveRandomly.startCoroutine = true;
}

因此,當我讓協程從游戲開始時開始時,因為 inCoroutine 默認為 false,所以一切正常,但是當我通過其他類使 startCoroutine 為 true 時,協程僅適用於 1 個對象。 我真的不知道為什么以及如何管理這個。

在你的場景中創建一個名為 NPCManager 的游戲對象,並在那里引用你所有的 npc。 如果它們在開始時已經存在於場景中,只需將它們拖放到編輯器中到您的公共數組中:

class NPCManager{
     public NpcMoveRandomly[] npcList;

     public void Method(){
          foreach(NpcMoveRandomly npc in npcList){
              npc.startCoroutine = true;
          }
     }
}

或者將 NPCManager 修改為單例並在將它們實例化到此數組/列表后直接添加 npc.....無論如何,有很多方法可以做到這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM