航点超出范围错误,我该如何解决?

问题描述 投票:0回答:1
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)
c# unity3d
1个回答
0
投票

“问题”是您计算1,2,3等,编译器0,1,2等。要解决此问题,您需要

if(transform.position == waypoints[index -1].position)

private int index = -1; 
© www.soinside.com 2019 - 2024. All rights reserved.