"SetDestination"can only be called on an active agent that has been placed on a NavMesh

Today, when using unity to make the game demo character navigation function, I encountered "SetDestination" can only be called on an active agent that has been placed on a NavMesh error. After searching for the reason, I found that after the navigation grid is correctly set, if the character has been placed on the navigation grid, the game will navigate normally when running the game, but if the character is loaded into the scene after running the game, the above error will be triggered.

  GameObject temp = Resources.Load<GameObject>(Constants.playerNormalPath);
  GameObject player = Instantiate(temp);
  player.transform.position = new Vector3(30, 0, 45);
  agent = player.GetComponent<NavMeshAgent>();
  agent.SetDestination(new Vector3(32, 0, 53));

Reason: After the game is running, use the Instantiate method to load the character into the scene, and then change its initial position, so that the character is too far away from the navigation grid at the moment of loading, making the navigation invalid!

There are three solutions:

1. Directly pass in position information when instantiating an object:

GameObject player = Instantiate(temp,new Vector3(30, 0, 45),Quaternion.identity);

2. After instantiating the object, set the position in the navigation grid:

NavMeshAgent agent = player.GetComponent<NavMeshAgent>();
agent.Warp(new Vector3(30, 0, 45));

3. On the character prefab, first set the enable of the NavMeshAgent component to false, and then set it to true when navigation is required.

Guess you like

Origin blog.csdn.net/l17768346260/article/details/104328258