Instantiate object through a coroutine problem

I have this script that spawn the npc in random waypoints position within a limit, in which the following conditions are checked:


  • **These waypoints must be out of the camera’s field of view **
  • Waypoints must be far from the player’s position
  • The maximum npc to be spawned is 150

Each of these waypoints contains the attached “Waypoints” script. When spawning these npc, it takes the “Waypoints” component as the currentWaypoint.waypoint. The strange thing is that while I had a simple scene the code worked perfectly without any error, but in the current situation, with a complex scene (with several buildings and irregular terrain), some of these nps keep the currentWaypoint.waypoint null


Here’s my code:

void Start()
{
    StartCoroutine(Spawn());
}

IEnumerator Spawn()
{
    int count = 0;

    while (count < pedestriansToSpawn)
    {
        Transform child = transform.GetChild(Random.Range(0, transform.childCount - 1));

        if (CanSpawn(child) && child.GetComponent<GetDistance>().distance > 50)
        {
            GameObject obj = Instantiate(PedestrianSelected());
            obj.transform.parent = parent;
            obj.name = string.Format("Pedestrian {0}", count + 1);
            obj.GetComponent<WaypointNavigator>().currentWaypoint.waypoint = child.GetComponent<Waypoints>();
            obj.GetComponent<NavMeshAgent>().Warp(new Vector3(child.position.x, child.position.y + 1, child.position.z));
        }
        else
            count--;

        yield return new WaitForSeconds(.25f);
        count++;
    }
}

@LollyHeartfield, the more complex the scene, the longer the NavmeshAgent takes to compute paths. That probably is at the core of your problem, but off the top of my head I’m not following the logic of your code to recommend a fix if that is indeed the issue.

Generally, wait some time before you try to tell the NPC to move to a newly acquired destination.

For example, if you were using NavMeshAgent.SetDestination, you can get the result of the boolean to tell if the path had finished computing or not and only start moving after it returns true.

The other thing is, are you sure the waypoints you’re adding are actually reachable?