IndexOutOfRangeExeption! This doesent even affect my gameplay, it just is there to be annoying!
using UnityEngine; using System.Collections;
public class Patrol : MonoBehaviour { public Transform[] patrolPoints; public float moveSpeed;
private int currentPoint;
// Use this for initialization
void Start () {
transform.position = patrolPoints[0].position;
currentPoint = 0;
}
// Update is called once per frame
void Update () {
if(currentPoint >= patrolPoints.Length)
{
currentPoint = 0;
}
if (transform.position == patrolPoints[currentPoint].position)
{
currentPoint++;
}
// This is where the error occurs!
transform.position = Vector3.MoveTowards(transform.position, patrolPoints[currentPoint].position, moveSpeed * Time.deltaTime);
}
}
try changing
if(currentPoint >= patrolPoints.Length)
to
if(currentPoint > patrolPoints.Length)
arrays are zero based...
If I change if(currentPoint >= patrolPoints.Length) to if(currentPoint > patrolPoints.Length), the cube in my game will go forward but will no longer go back to its starting position.
my typo... change it to
if(currentPoint > patrolPoints.Length - 1)
It will return to its starting position now, but I still get the error.
Answer by RybiconZX · Apr 12, 2016 at 08:45 PM
I would switch your if statements, you want to increment your index counter and then check to see if it is going out of bounds in that order. Because you have the if statements in that order the MoveTowards function has a chance to be indexing an out of bounds array element.
//Increment first
if(transform.position == patrolPoints[currentPoint].position) {
currentPoint++;
}
//Check for out of bounds
if(currentPoint >= patrolPoints.Length) {
currentPoint = 0;
}
also gjf advice to change the if statement from currentPoint >= patrolPoints.Length is incorrect, you had it correct originally.
Your answer
Follow this Question
Related Questions
[SOLVED]Removing gameobject from list don't change the index 1 Answer
IsGrounded not updating properly 1 Answer
problems with mopub 0 Answers
It does not work removing items from the inventory 0 Answers
how can i control scale speed ? 1 Answer