Array index is out of range error

I’ve been receiving errors when playing after my enemy object has reached the last waypoint.

I can’t seem to figure out a way to fix this. can anyone help me figure this out?
Also when I try to make the enemy face the waypoints, when reaching a slope (stairs) he begins to face an angle towards the waypoint is there any way to fix this?


using UnityEngine;
using System.Collections;

public class OneWaypoint : MonoBehaviour {
	public Transform[] waypoint;
	public float speed = 5;
	private int currentWaypoint;
	bool loop = true;

	void Update () {
		Vector3 target = waypoint[currentWaypoint].position;
		Vector3 moveDirection = target - transform.position;
		var velocity = rigidbody.velocity;
		if(currentWaypoint < waypoint.Length){
			if(moveDirection.magnitude < 1){
				velocity = moveDirection.normalized * speed;	
			rigidbody.velocity = velocity;
				currentWaypoint = 0;
				rigidbody.velocity =;	

You test for a value beyond the end of the range on line 14, but this test is done after you access your waypoint array on line 9. So what happens is that in some frame you increment currentWaypoint beyond the end of the array and then in the next frame you use that value to index into the array.

A couple of other minor issues. You don’t initialize currentWaypoint. In addition, line 11 would fail if waypoint array did not have any entries.