0
votes

Here is my code:

ShopButton[] allButtons = FindObjectsOfType<ShopButton> ();

for (int i = 0; i < allButtons.Length; i++) 
{
    allButtons [i].UpdateButtonState ((GameDataManager.publicInstance.skinAvailability & 1 << allButtons [i - 1].ninjaNumber) == 1 << allButtons [i - 1].ninjaNumber);
}

When I run it this code gives me an IndexOutOfRangeException.

1
Because on the first loop, i will be 0 and i - 1 will be -1, which is not a valid index for an array. - Ian H.
Change fro loop to start at 1 instead of zero : for (int i = 1; i < allButtons.Length; i++) - jdweng
i have already tried i-1 and like @IanH. said i-1 results in the index being -1 which results in the same error... - RaZ
@jdweng what you suggested worked so if you put your comment into an answer and explain why i have to start at 1 and then use i-1 instead of starting at 0 and just using i, your answer will be happily accepted... - RaZ

1 Answers

2
votes

I think the reason is because of the first index that causes a problem. if i starts with 1 then i-1 will be 0 and therefore the index 0 exists in array allbuttons. Clearly : if starting i is 0, then i-1 will be -1; this will cause index out of range exception because all arrays start with index 0 and have no index -1. ;

Starting with i = 1 the error will be solved because then i-1 will be 0 which is in range of indexes of any array.

change part of loop to :

for (int i = 1; i < allButtons.Length; i++)