0
\$\begingroup\$

I've been working on a wave-based zombie game for the past few months and all of the systems have been working perfectly - until I upgraded to the latest version of Unity. Since then, spawning a zombie onto a nav mesh and then calling SetDesination is throwing the exception:

"SetDestination" can only be called on an active agent that has been placed on a NavMesh.
UnityEngine.AI.NavMeshAgent:SetDestination(Vector3)

The zombies are spawned a random spawn point and their destination set as so:

 GameObject go;
        for (int i = 0; i < SpawnAmount; i++)
        {
            Vector3 location = new Vector3(transform.position.x + i + UnityEngine.Random.Range(-1, 1), transform.position.y, transform.position.z + i + UnityEngine.Random.Range(-1, 1));
            go = Instantiate(enemyPrefab, location, spawnRotation) as GameObject;
            go.GetComponent<NavMeshAgent>().SetDestination(players[0].transform.position);
        }

It is the setdestination line that is causing me issues.

I have a static baked nav area. The player characters (who also use nav agent to move) can move across the nav area perfectly - it is only the zombies which seem to have trouble.

I have spent a long while tweaking settings here and there. Adjusting the location of the zombie and even having a zombie in the game before starting the game. However I can't seem to correct this exception - all while the player characters are moving perfectly.

Any ideas on what I could be missing or areas I should be looking?

A spawned zombie with its nav agent details

The nav mesh

Nav mesh agent settings

EDIT The updated and working code:

GameObject go;
for (int i = 0; i < SpawnAmount; i++)
{
    Vector3 location = new Vector3(transform.position.x + i + UnityEngine.Random.Range(-1, 1), transform.position.y, transform.position.z + i + UnityEngine.Random.Range(-1, 1));
    go = Instantiate(enemyPrefab, location, spawnRotation) as GameObject;
    go.GetComponent<NavMeshAgent>().Warp(location);
    go.GetComponent<NavMeshAgent>().SetDestination(players[0].transform.position);
}
\$\endgroup\$
0
\$\begingroup\$

Just a shot in the dark here but I think that if you set a agents position with transform.position it does not know it's on the nav mesh. try using NavMeshAgent.Warp(spawnPosition) after you instantiate the zombie and the set its destination.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thanks for that. Worked like a treat! Not sure what changed between the Unity versions but glad it's working. Updated code in main post \$\endgroup\$ – user1662292 Oct 30 '17 at 17:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.