using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.AI;
public class wps : UnityEngine.MonoBehaviour
{
public List<Transform> waypoints = new List<Transform>();
public float speed = 2.0f;
public bool faceHeading = true;
public bool loop = false;
private int index = 0;
// Use this for initialization
protected void Start()
{
var ways = GameObject.FindGameObjectsWithTag("wp");
foreach (GameObject go in ways)
{
waypoints.Add(go.transform);
}
}
private void Update()
{
if(index != waypoints.Count)
{
transform.position = Vector3.MoveTowards(transform.position, waypoints[index].position, speed * Time.deltaTime);
}
if(transform.position == waypoints[index].position)
{
index++;
}
}
}
该对象到达最后一个终点,但是显示错误ArgumentOutOfRangeException:索引超出范围。必须为非负数并且小于集合的大小。参数名称:第33行的索引
if(transform.position == waypoints[index].position)
“问题”是您计算1,2,3等,编译器0,1,2等。要解决此问题,您需要
if(transform.position == waypoints[index -1].position)
或
private int index = -1;