Turn based games turn manager is spazzing out

I have a game with several units on the field, some computer controlled, some player controlled. when the unit’s AP reaches 0, a boolean called ‘isitmyturn’ is turned off. and the script should make the next unit’s ‘isitmyturned’ boolean enabled in the queue.

However, as soon as the first unit’s turn ends, the index value immediately sets itself out of the arrays index range. I’m not sure where it is going wrong, here is the script,

var order : GameObject[];

var selectedunit : GameObject;
var index : int = 1;

var numberofunits : int = 2;



function nextturn(){

if(selectedunit.tag == "Enemy"){
selectedunit.GetComponent(enemyAI).isitmyturn = true;
}
if(selectedunit.tag == "Player"){
selectedunit.GetComponent(player_script).isitmyturn = true;
}
index += 1;
}






function Update(){

var selectedunit : GameObject = order[index];

if(index > (numberofunits-1)){

index = 0;
}

if(selectedunit.tag == "Enemy"){
if(selectedunit.GetComponent(enemyAI).isitmyturn == false){

nextturn();

}}

if(selectedunit.tag == "Player"){
if(selectedunit.GetComponent(player_script).isitmyturn == false){

nextturn();

}}

}

Short answer: set your starting index to 0.

JavaScript arrays have a 0 based index which means that the first object should have an index of 0.

In you code you state that the total number of objects is 2. This means that in your array you’d have an object at index 0 and an object at index 1. If you set your starting index as 1 in your logic then that means you are selecting the second object in the array. As soon as you increment the index you are targeting and try to select that object you get the index out of range exception.

You have two declarations for selectedunit (line 3 and 28). This is normally bad. I would suggest changing line 28 to the following.

selectedunit = order[index];

Not 100% sure this is the problem, I work in C# and it would give me a complier warning if I tried to write as you have done. Not sure if JavaScript responds the same.