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

今天在使用unity制作游戏demo角色导航功能的时候,遇到了"SetDestination"can only be called on an active agent that has been placed on a NavMesh报错。找了找原因后发现,在正确的设置好导航网格后,如果角色已经放置在导航网格上,运行游戏则正常导航,但如果角色是运行游戏后加载进场景,会触发上述报错。

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

原因:游戏运行后使用Instantiate方式将角色载入场景后,再改变其初始位置,使得角色在载入的一瞬间距离导航网格过远,使得导航失效!

解决办法有三种:

1.实例化物体时直接传入位置信息:

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

2.实例化物体后设置所在导航网格内位置:

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

3.角色预制体上首先将NavMeshAgent组件的enable设置为false,等到需要导航时再将其设置为true。

你可能感兴趣的:(unity)