首页 > 解决方案 > 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 函数中,它就可以工作。

标签: unity3d

解决方案


在您发布的代码中,您没有调用该函数,您只是在定义该函数。在描述中,您说您正在调用该函数。您在哪里尝试调用该函数?如果您要定义一个函数,您应该在 Update()、Start() 或 Awake() 中调用它。请记住,当您调用该函数时,您必须在参数中的 Vector3 上调用 new。

DispatchTroops(new Vector3 (x,y,z));

推荐阅读