简体   繁体   中英

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

Im trying to apply the same Coroutine for 5 objects, when the coroutine starts at the lauch of the game the 5 objects do that Coroutine but when I make them start trough other class only 1 object start the coroutine.

This is the code that make the 5 objects start the coroutine:

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

Now the code that only 1 object start the coroutine (I'll show just the differences):

//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;

}

In other class:

public NpcMoveRandomly npcMoveRandomly;

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

So when I make the coroutine start with the lauch of the game, because the inCoroutine its false for default, its all ok but when I make the startCoroutine true trough other class the coroutine only applies to 1 object. I really don't know why and how to manage this.

Create a gameobject named NPCManager in your scene and reference there all your npcs. If they exist already in the scene at the beginning, just drag and drop them in the editor into your public array:

class NPCManager{
     public NpcMoveRandomly[] npcList;

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

Or modify NPCManager to a singleton and add the npc directly after instatiating them to this array/list.....what ever, there are a lot of ways to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM