-1

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;
        }
    }
Roy
  • 17
  • 6

1 Answers1

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.

0xJulian
  • 26
  • 3