I am making a game and trying to get the enemies patrol an area of waypoints. Currently each enemy has only 2 waypoints. When I start the game, I immediately get an IndexOutOfRangeException even though the array has been instantiated and the currentWaypoint variable is set to 0. Here is the code that I am currently using.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour {
public GameObject[] Waypoints = new GameObject[2];
public int CurrentWaypoint = 0;
private GameObject Player;
void Start () {
Player = GameObject.Find ("Player");
SetTarget (Waypoints[CurrentWaypoint]); //Get IndexOutOfRangeException here
}
void Update () {
GetComponent<Animator> ().SetFloat ("DistanceToPlayer", Vector3.Distance (transform.position, Player.transform.position));
}
public void SetTarget(GameObject target) {
GetComponent<UnityEngine.AI.NavMeshAgent> ().SetDestination (target.transform.position);
}
public void IncrementWaypoint() {
CurrentWaypoint++;
if (CurrentWaypoint == Waypoints.Length)
CurrentWaypoint = 0;
SetTarget (Waypoints[CurrentWaypoint]);
}
}
I don't understand why I am getting this error when, clearly, there are elements in the array.