我想做一个简单的脚本,将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];
}
}
答案 0 :(得分:2)
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()
函数仅在代理到达当前点时调用。
希望对您有帮助