Texture2d[]: Array index is out of rang (Javascript)

Hello Everyone, I was wondering if someone could help me on fixing this error, I do realize that the reason of this error is that I didn’t set a limit to the amount of arrays I’m using. However I have no idea on how to do so, but would highly appreciate if someone could help me. The max number arrays im currently using is 13.

Note: I just the arrays to stop after I press on the object 13th time, so basically a limit to 13 where no sound is play and etc…

Script:

#pragma strict

static var charge : int = 0;
var swipe : AudioClip;

// Calendar arrays

var calCharge : Texture2D[];
var calendar : Renderer;

function Start () {

  charge = 0;

}

function Calendarchange () {

	AudioSource.PlayClipAtPoint (swipe, transform.position) ;
	charge++;
    calendar.material.mainTexture = calCharge[charge];
    print ("works");

}

If you want them to loop you should try calCharge[charge % calCharge.Length] (that’s a modulus so its always inside the length of the array.

Use Array.Length and make sure “charge” does not equal or exceed it.

If you’re getting the “Array index is out of range” error then your [charge] variable must be going over the Length of your calCharge array. You’ll need to add some code to check that charge++; doesn’t go outside the Length (or size as it’s called in the Inspector) of your array.

function Calendarchange () {

    if ( charge < calCharge.Length ) {
        AudioSource.PlayClipAtPoint (swipe, transform.position) ;
        charge++;
        calendar.material.mainTexture = calCharge[charge];
        print ("works");
    }
}

Adding this if statement will check to see if charge is less than the Length of your calCharge array. If it is, it will let the function continue. If not, it will do nothing. You can easily add in some code to do something else in that case.