aikachiqq aikachiqq - 1 month ago 5
Javascript Question

Array is out of range .. Any solution?

Im doing a cheat for my game. I dont know what to do. Array is out of range ..When i run the game and i type the keycode in myStrings it wont stop adding coins and when i move, it suddenly terminated.Thank you.

private var cheatCode : String[];
var myStrings : String[] = [ "i", "d", "k", "f", "a" ];
private var index: int;
public static var coins : int;
private var coinsBegin : int;


function Start() {
coins = PlayerPrefs.GetInt("Coinss");

cheatCode = myStrings;
index=0;
}

function Update() {

if (Input.anyKeyDown) {

if (Input.GetKeyDown(cheatCode[index])) {

index++;
}

else {
index = 0;
}
}


if (index == cheatCode.Length) {

coins += 100;
PlayerPrefs.SetInt ("Coinss", coins);
coinsBegin++;
PlayerPrefs.GetInt("Coinss");
}

}
function OnGUI () {
GUI.Label (Rect (20, 20, 200, 40), "score: " +PlayerPrefs.GetInt("Coinss"));

}
//Error:


This one is the picture of the error

I dont know what to do. Array is out of range ..When i run the game and i type the keycode in myStrings it suddenly terminated.Thank you.

I dont know what to do. Array is out of range ..When i run the game and i type the keycode in myStrings it suddenly terminated.Thank you.

Answer

After you type in the cheat code, the cheat is being applied every time the update method is called. If you type in another character of the cheat code the index is incremented and causes the array out of range. Try resetting the index when the cheat code is accepted:

      if (index == cheatCode.Length) {

        coins += 100;
        PlayerPrefs.SetInt ("Coinss", coins);
        coinsBegin++;
        PlayerPrefs.GetInt("Coinss");
        index = 0; //reset index
      }