- Home /
IndexOutOfRangeExeption: Array index is out of range
I Tried to make a waypoint system with the following code. I get the error above, but the strange this is that everything works fine... What could it be? (Error at line 28).
using UnityEngine;
using System.Collections;
public class EnemyWitchEngine : MonoBehaviour {
public Transform[] waypoints;
public float normalSpeed = 2;
public float attackSpeed = 3;
public int currentWaypoint = 0;
//private Transform target;
void Start ()
{
//target = GameObject.Find ("First Person Controller").transform;
}
void Update ()
{
//Vector3 correctTarget = new Vector3(target.position.x, transform.position.y, target.position.z);
//transform.LookAt(correctTarget);
if (waypoints.Length == 0)
{
print("You need to assign some waypoints within the Inspector");
}
if(currentWaypoint >= waypoints.Length || currentWaypoint < 0)
{
currentWaypoint = 0;
}
if(Vector3.Distance(waypoints[currentWaypoint].position, transform.position) <= 0.1f)
{
//next waypoint
currentWaypoint ++;
}
else
{
transform.position = Vector3.MoveTowards(transform.position, waypoints[currentWaypoint].position, normalSpeed * Time.deltaTime);
transform.LookAt(waypoints[currentWaypoint]);
}
}
}
Any chance you have this script on more than one object?
Are you sure the problem is at line 28? I only see an array access at 33, 40, and 41.
Answer by Imagineer · Mar 18, 2014 at 08:12 PM
Ah You we're right. I had the same script on one more object, but I didnt assign waypoints to that one.. So thanks very much for the help! :D (The error came from that gameobject and not this one..)
I suggest adding your check for waypoints in Awake() and using Debug.LogError() and Debug.Break(). By doing so you won't spam your console. You could also output the .name of the GameObject to help with debugging.
In your Update() function you could return.
Equally you can make Start() a Coroutine which would allow you to yield for a short period so you don't check all the time and also you could yield break right at the start of your Start() in order to avoid updating constantly if you have no waypoints.
Thansk for these tips, but for most of them, I don't know enough... But I added a checkmark boollean "Use Waypoints" So I can enable/disable this part of the script for each individual GameObject.