在层次结构中,我有主相机,ThirdPersonController,平面,地形,圆柱体,墙。
在“资源”中,我创建了一个名为“我的脚本”的新文件夹,在那里我用c#创建了一个名为Patroll.cs的新脚本,该脚本应该让ThirdPersoncontroller角色在两个给定点之间行走以进行巡逻。但是当我将巡逻脚本添加/拖动到ThirdPersonController时,我得到了错误:
错误出现在Patroll.cs脚本中的以下行:
if (agent.remainingDistance < 0.5f)错误是:
MissingComponentException:"ThirdPersonController“游戏对象没有附加”NavMeshAgent“,但脚本正在尝试访问它。您可能需要向游戏对象"ThirdPersonController“添加一个NavMeshAgent。或者,在使用组件之前,脚本需要检查组件是否已附加。
这是Patroll.cs脚本代码
using UnityEngine;
using System.Collections;
public class Patroll : MonoBehaviour {
public Transform[] points;
private int destPoint = 0;
private NavMeshAgent agent;
// Use this for initialization
void Start () {
agent = GetComponent<NavMeshAgent>();
// Disabling auto-braking allows for continuous movement
// between points (ie, the agent doesn't slow down as it
// approaches a destination point).
agent.autoBraking = false;
GotoNextPoint();
}
void GotoNextPoint() {
// Returns if no points have been set up
if (points.Length == 0)
return;
// Set the agent to go to the currently selected destination.
agent.destination = points[destPoint].position;
// Choose the next point in the array as the destination,
// cycling to the start if necessary.
destPoint = (destPoint + 1) % points.Length;
}
void Update () {
// Choose the next destination point when the agent gets
// close to the current one.
if (agent.remainingDistance < 0.5f)
GotoNextPoint();
}
}然后,我尝试在ThirdPersonController的层次结构中单击,然后在菜单中单击组件>导航>导航网格代理
现在,在检查器的ThirdPersonController中,我看到了添加的导航网格代理。
现在,当我运行游戏时,我得到了同样的错误:
MissingComponentException:"ThirdPersonController“游戏对象没有附加”NavMeshAgent“,但脚本正在尝试访问它。您可能需要向游戏对象"ThirdPersonController“添加一个NavMeshAgent。或者,在使用组件之前,脚本需要检查组件是否已附加。
我试着在菜单中点击窗口>导航,然后点击烘焙。但它并没有解决这个问题。
在Patroll.cs脚本的同一行中出现相同的错误。
但是我在ThirdPersonController中添加了一个导航网格代理,那么为什么在错误中它说它没有附加呢?如何使代理处于启用状态?
在ThirdPersonController中,在添加完之后,在检查器中的巡逻脚本,我看到在巡逻部分,我可以添加点,改变另一个值,但是属性: Dest点和代理是灰色的,不能使用。
在代理中我看到:代理无(导航网格代理),但我不能点击它,它是灰色的,未启用。
更新:
这是右侧的ThirdPersonController检查器、巡逻脚本和导航网格代理的屏幕截图。

在Patroll.cs脚本中,我将变量agent改为public:
public NavMeshAgent agent;现在,ThirdPersonController在检查器中添加了导航网格代理和巡更脚本,我还在巡更中添加了: ThirdPersonController (导航网格代理),但现在我收到了错误:
只能在已放置在NavMesh上的活动代理上调用"GetRemainingDistance“。UnityEngine.NavMeshAgent:get_remainingDistance()巡逻:更新()(位于Assets/My Scripts/Patroll.cs:41)
patroll脚本中的第41行是:
if (agent.remainingDistance < 0.5f)

发布于 2016-07-24 02:04:57
您尚未在Patroll脚本组件中分配包含对象的NavMeshAgent组件。

代理变量字段应为公共或可序列化的私有。
public NavMeshAgent Agent;https://stackoverflow.com/questions/38542869
复制相似问题