@NoobNoob

IndexOutOfRangeException: Array index is out of range? что делать?

Я делал скрипт движения монстров по WayPoints и наткнулся на это:
610a702ad8fff934091943.png
Я не знаю в чем проблема.
Вот код спавна:
using System.Collections;
using UnityEngine;

public class WaveSpawn : MonoBehaviour {

    public int WaveSize;

    public GameObject Enemy;

    public float EnemyInterval;

    public Transform spawnPoint;

    public float startTime;

    int enemyCount = 0;

    public Transform[] WayPoints;

    // Start is called before the first frame update
    void Start() {
        InvokeRepeating("SpawnEnemy", startTime, EnemyInterval);
    }

    void Update()
    {
        if (enemyCount == WaveSize)
        {
            CancelInvoke("SpawnEnemy");
        }
    }  
    void SpawnEnemy()
    {
        enemyCount++;
      GameObject enemy = GameObject.Instantiate(Enemy, spawnPoint.position, Quaternion.identity) as GameObject;
        enemy.GetComponent<MoveToWayPoints>().waypoints = WayPoints;
    }

}

И код движения:
using System.Collections;
using UnityEngine;

public class MoveToWayPoints : MonoBehaviour {

    public float Speed;

    public Transform[] waypoints;

    int curWaypointsIndex = 0;

  

    // Update is called once per frame
    void Update()
    {
        if (curWaypointsIndex <= waypoints.Length) {
            transform.position = Vector3.Lerp(transform.position, waypoints[curWaypointsIndex].position, Time.deltaTime * Speed);
            if (Vector3.Distance(transform.position, waypoints[curWaypointsIndex].position) < 0.5f)
            {
                curWaypointsIndex++;
            }
        }
    }
}
  • Вопрос задан
  • 53 просмотра
Решения вопроса 1
vabka
@vabka Куратор тега C#
Токсичный шарпист
// Update is called once per frame
    void Update()
    {
        if (curWaypointsIndex <= waypoints.Length) {
            transform.position = Vector3.Lerp(transform.position, waypoints[curWaypointsIndex].position, Time.deltaTime * Speed);
            if (Vector3.Distance(transform.position, waypoints[curWaypointsIndex].position) < 0.5f)
            {
                curWaypointsIndex++;
            }
        }
    }

Ошибка происходит тут, тк waypoints.Length на единицу больше, чем индекс последнего элемента.
Вместо '<=' (меньше либо равно) пиши '<' (меньше)
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы