-1

Array index is out of range in Unity, need some help!

void OnCollisionEnter2D(Collision2D col) {
    rigidbody2D.velocity = new Vector2(0, 0);
    transform.rotation = Quaternion.Euler (0, 0, headDownAngle);
    if(!isDied) {
        audios[1].Play();
        animator.SetTrigger("dead");
        iTween.ShakePosition(Camera.main.gameObject, new Vector3(0.3f, 0.3f, 0), 0.5f);
    }       
    isDied = true;
    isPlaying = false;
derHugo
  • 83,094
  • 9
  • 75
  • 115
Reynir Freyr
  • 137
  • 3
  • 9

2 Answers2

0

I don't see any other arrays being used (Unless one of your other functions use arrays) so it seems this line is causing the error:

 audios[1].Play();

Remember Arrays are zero based so the first position in an array is actually 0, so if you are trying to get the first element do:

audios[0].Play().

If you are trying to get the second element, make sure audios has 2 elements.

0

Array index is out of range is an error caused when you try to use a part of an array that doesn't exist example

float numOfTests = 2;
AudioSource[numOfTests] tests;

void Start()
{
    tests[3].play();
} 

since there are only 2 audio sources in the array we can access a third one because it doesn't exist.

I hope this is helpful. I used to code in unity put I moved over to c++ and writing custom engines so if my answer doesn't help that might because I haven't used unity in a year.

Realuther
  • 63
  • 1
  • 10