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