'Outside the bounds of the array in Unity [duplicate]
I am having 4 angles that is stored in an array:
90 180 270 360
I am using one of these when a trigger gets activated. However I am getting an error saying index was outside the bounds. Why is this happening?
public float[] rotateAngles;
int i = 0;
public void OnTriggerEnter (Collider col) {
if (!enabled) return;
Rotate ();
}
public void Rotate(){
transform.eulerAngles = new Vector3(transform.eulerAngles.x, rotateAngles[i], transform.eulerAngles.z);
i++;
if(i>rotateAngles.Length){
i = 0;
}
}
Solution 1:[1]
You get this error because an index starts with 0, and the length starts counting with 1. So if you have an float[] with the length 5 your last index of the array is 4.
Just change your if condition to the following:
if(i == rotateAngles.Length - 1){
i = 0;
}
And your program should be working fine.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 0xJulian |
