unity3d - Unity3D SetDestination 更新
问题描述
在我的测试中,我发现 navMeshAgent.SetDestination 放在 Update 函数中时可以工作,但在其他函数中它不起作用。我想知道它是如何发生的,并恳求您的回答。
士兵.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Soldier : MonoBehaviour {
private UnityEngine.AI.NavMeshAgent navMeshAgent;
void Awake() {
}
void Start() {
navMeshAgent = GetComponent<UnityEngine.AI.NavMeshAgent>();
}
void Update() {
}
public void DispatchTroops(Vector3 destination) {
navMeshAgent.SetDestination(destination);
}
}
添加士兵.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AddSoldiers : MonoBehaviour {
public GameObject soldier;
static readonly int soldiersNumber = 10;
private Vector3 src;
bool order = false;
// Use this for initialization
void Start() {
Button btw = this.GetComponent<Button>();
btw.onClick.AddListener(TaskOnClick);
src = Vector3.zero;
}
// Update is called once per frame
void Update() {
if (order) {
StartCoroutine(GenerateSoliders(new Vector3(5f, 5f, 5f)));
order = false;
}
}
// Click button
public void TaskOnClick() {
order = true;
}
// Add a few soldiers
IEnumerator GenerateSoliders(Vector3 destination) {
for (int i = 0; i < soldiersNumber; i++) {
GameObject s = Instantiate(soldier, src, Quaternion.identity);
s.GetComponent<Soldier>().DispatchTroops(destination);
yield return new WaitForSeconds(1);
}
}
}
代码如上。在指挥官gameObjcet中,首先创建一个士兵游戏对象,然后调用士兵的成员函数DispatchTroops。但是出现了错误:
NullReferenceException: Object reference not set to an instance of an object Soldier.DispatchTroops(Vector3 destination) (at Assets/Scenes/Soldier.cs:19).
如果我将 navMeshAgent.SetDestination 放在 Update 函数中,它就可以工作。
解决方案
在您发布的代码中,您没有调用该函数,您只是在定义该函数。在描述中,您说您正在调用该函数。您在哪里尝试调用该函数?如果您要定义一个函数,您应该在 Update()、Start() 或 Awake() 中调用它。请记住,当您调用该函数时,您必须在参数中的 Vector3 上调用 new。
DispatchTroops(new Vector3 (x,y,z));
推荐阅读
- android - 带有颤动的 Firebase 动态链接:深层链接 URL 未打开应用程序
- ios - StackView 中的 iOS UIButtons 没有被点击
- angular - Angular - 组件之间未传递服务数据
- c# - 有没有办法让我在没有窗口的情况下将图像绘制到我的屏幕上?
- hadoop - 多个连接与配置单元表上的计数
- laravel - 在 laravel 中为每个 crud 操作定义权限的位置
- python - 如何使用 groupby 按日历月显示标准偏差并绘制它?
- angular - Angular8 中的动态渲染
- laravel-5 - 完整性约束违规:1052 列“主题”在 where 子句中不明确
- php - LARAVEL 如何从公共文件夹中删除图像?