2

我想制作一个简单的脚本,将 NavMesh 代理引导到各种航点。我是 Unity 的新手,所以我还不知道一些基本功能,而是输入伪代码。

using UnityEngine;
using UnityEngine.AI;

public class Path_left_blue : MonoBehaviour {

    private Transform target;
    private int wavepointindex = 0;
    public NavMeshAgent agent;

    void Start () {
        target = Waypoints_blue_left.waypoints[0];
    }

    void Update () {
        //Set destination to waypoint
        Vector3 dir = target.position;
        agent.setDestination(dir);

        if (agent is within a close range/touching target waypoint)

            //Remove object if at the last waypoint
            if (wavepointindex == Waypoints_blue_left.waypoints.Length)
                Destroy(gameObject);

            wavepointindex++;
            target = Waypoints_blue_left.waypoints[wavepointindex];

    }
}
4

1 回答 1

3

void Update()函数调用每一帧。所以你需要一个函数来检查代理是否到达点,将新的目的地设置为它。

我将您的代码更改为:

using UnityEngine;
using UnityEngine.AI;

public class Path_left_blue : MonoBehaviour 
{
    private Transform target;
    private int wavepointindex = -1;
    public NavMeshAgent agent;

    void Start () 
    {
        EnemyTowardNextPos();
    }

    void Update () 
    {
        // agent is within a close range/touching target waypoint
        if (!agent.pathPending && agent.remainingDistance < 0.5f)
        {
            EnemyTowardNextPos();
        }
    }

    void EnemyTowardNextPos ()
    {
        if(wavepointindex == Waypoints_blue_left.waypoints.Length - 1)
        {
            Destroy(gameObject);
        }
        else
        {
            // set destination to waypoint
            wavepointindex++;
            target = Waypoints_blue_left.waypoints[wavepointindex];
            agent.SetDestination(target);
        }
    }
}

EnemyTowardNextPos()仅在代理到达当前点时调用该函数。

希望对你有帮助

于 2018-08-29T09:53:49.970 回答