0

我正在尝试以网格方式在 NavMesh 上实例化 NPC 预制件。预制件具有组件 NavMeshAgent,并且 NavMesh 已烘焙。我收到错误:

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

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

这在放置在 NavMesh 上的空 GameObject 上使用以下脚本:

 // Instantiates a prefab in a grid

    public GameObject prefab;
    public float gridX = 5f;
    public float gridY = 5f;
    public float spacing = 2f;

    void Start()
    {
        for (int y = 0; y < gridY; y++)
        {
            for (int x = 0; x < gridX; x++)
            {
                Vector3 pos = new Vector3(x, 0, y) * spacing;
                Instantiate(prefab, pos, Quaternion.identity);
            }
        }
    }
4

3 回答 3

2

我首先要说 NavMesh 有时非常棘手。涉及到很多小怪癖等,我最终离开了 NavMesh,并使用了 A*(A 星)光线投射样式库。对于数十个同时移动的实体来说效率不高,但对于动态地图和对象/模型攀爬来说非常通用。

另外我想说的是,能够使用简单的 API 命令并不足以使用 Nav Mesh - 您需要了解大量协同工作的组件,而 Unity 文档并没有应有的帮助。如果您使用动态实体并需要重新雕刻等,请准备好拉出一些头发。

无论如何,我要警告您的第一件事是,如果您的实体周围有对撞机,它们可能会干扰自己的导航(因为他们自己的对撞机可以切入导航网格,将实体留在一小块非网格上)。

其次,我建议您将实体 Warp() 放到导航网格上。这会获取您实体的位置(可能不是真正在导航网格上)并将其扭曲到关闭可用的导航网格节点/链接,此时它应该能够导航

祝你好运!

于 2018-11-30T04:46:48.913 回答
1

好的,解决了问题。根据我的 OP,我确实有一个烘焙的 Nav Mesh,并且 prefabs 有 Nav Mesh Agent 组件。问题是 Nav Mesh 的分辨率和 Nav Mesh Agent 上的 Base Offset 设置为 -0.2。

使用 Height Mesh 设置重新烘焙 Nav Mesh 使可行走区域更加准确。

在此处输入图像描述

连同将 Nav Mesh Agent 上的 Base Offset 更改为 0。

在此处输入图像描述

于 2018-12-06T01:41:03.420 回答
0

关于:

“SetDestination”只能在已放置在 NavMesh 上的活动代理上调用。UnityEngine.AI.NavMeshAgent:SetDestination(Vector3)

我相信问题在于您没有将相应的NavMeshAgent逻辑添加到您正在实例化的预制件中。请执行下列操作:

  • 将导航网格代理添加到您正在实例化的预制件中
  • 设置,只是为了测试,一个目的地点(这可以是一个空的游戏对象),并将其命名为“目的地”
  • 将以下脚本添加到要实例化的 GameObject

像这样的东西:

public class Movement : MonoBehaviour {
        //Point towards the instantiated Object will move
        Transform goal;

        //Reference to the NavMeshAgent
        UnityEngine.AI.NavMeshAgent agent;

        // Use this for initialization
        void Start () {
            //You get a reference to the destination point inside your scene
            goal = GameObject.Find("Destination").GetComponent<Transform>();

            //Here you get a reference to the NavMeshAgent
             agent = GetComponent<UnityEngine.AI.NavMeshAgent>();

            //You indicate to the agent to what position it has to move
            agent.destination = goal.position;
        }

}

如果您的实例化预制件需要追逐某些东西,您可以从 Update() 更新目标位置。喜欢:

void Update(){
    agent.destination = goal.position;
}
于 2018-11-30T06:28:58.717 回答