【发布时间】:2016-07-23 14:29:06
【问题描述】:
在层次结构中,我有 Main Camera、ThirdPersonController、Plane、Terrain、Cylinder、Wall。
在 Assets 中,我创建了一个名为 My Scripts 的新文件夹,并在 C# 中创建了一个名为 Patroll.cs 的新脚本,该脚本应使 ThirdPersoncontroller 角色在两个给定点之间行走以进行巡逻。但是当我将 Patroll 脚本添加/拖动到 ThirdPersonController 时出现错误:
错误出现在Patroll.cs脚本就行了:
if (agent.remainingDistance < 0.5f)
错误是:
MissingComponentException:“ThirdPersonController”游戏对象没有附加“NavMeshAgent”,但脚本正在尝试访问它。 您可能需要将 NavMeshAgent 添加到游戏对象“ThirdPersonController”。或者您的脚本需要在使用之前检查组件是否已附加。
这是 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 上的层次结构中单击,然后在菜单中单击 Component > Navigation > Nav Mesh Agent
现在在 Inspector 的 ThirdPersonController 中,我看到了添加的 Nav Mesh Agent。
现在我在运行游戏时遇到了同样的错误:
MissingComponentException:“ThirdPersonController”游戏对象没有附加“NavMeshAgent”,但脚本正在尝试访问它。 您可能需要将 NavMeshAgent 添加到游戏对象“ThirdPersonController”。或者您的脚本需要在使用之前检查组件是否已附加。
我尝试单击 Window > Navigation 上的菜单,然后单击 Bake。 但它并没有解决它。
Patroll.cs 脚本中同一行的相同错误。
但是我向 ThirdPersonController 添加了一个导航网格代理,那么为什么在错误中它说它没有附加?以及如何使代理启用?
在 ThirdPersonController 中添加了 Inspector 中的 Patroll 脚本后,我在 Patroll 部分看到我可以添加点更改另一个值,但属性:Dest Point 和 Agent 是灰色的不能使用。
在代理中我看到:代理无(导航网格代理)但我无法单击它,它是灰色的,未启用。
更新:
这是 Patroll 脚本和 Nav Mesh Agent 右侧的 ThirdPersonController Inspector 的屏幕截图。
在 Patroll.cs 脚本中,我将变量 agent 更改为 public:
public NavMeshAgent agent;
现在 ThirdPersonController 在 Inspector 中有 Nav Mesh Agent 和 Patroll 脚本,我还在巡逻中添加了代理:ThirdPersonController (Nav Mesh Agent) 但现在我收到错误:
“GetRemainingDistance”只能在已放置在 NavMesh 上的活动代理上调用。 UnityEngine.NavMeshAgent:get_remainingDistance() Patroll:Update()(在 Assets/My Scripts/Patroll.cs:41)
巡逻脚本中的第 41 行是:
if (agent.remainingDistance < 0.5f)
【问题讨论】:
-
你确定
NavMeshAgent附加到了同一个游戏对象Patroll附加到了吗? -
@Programmer 如果附加意味着将脚本拖到对象上,那么是的。导航网格代理和 ThirdPersonController 中的脚本。
-
@Programmer 我在我的问题中添加了一个屏幕截图,您可以在右侧看到 Patroll 脚本的 ThirdPersonController Inspector 和同一对象上的 Nav Mesh Agent。并且可以在 Inspector 中看到 Patroll 脚本中的 Agent 没有启用。
标签: c# unity3d unityscript unity5