N
N
NoobNoob2021-08-04 13:50:30
C++ / C#
NoobNoob, 2021-08-04 13:50:30

IndexOutOfRangeException: Array index is out of range? what to do?

I was making a script to move monsters on WayPoints and came across this:
610a702ad8fff934091943.png
I don't know what the problem is.
Here is the spawn code:

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;
    }

}

And the movement code:
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++;
            }
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-08-04
@NoobNoob

// 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++;
            }
        }
    }

The error occurs here because waypoints.Length is one more than the index of the last element.
Instead of '<=' (less than or equal to) write '<' (less than)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question