- Home /
The question is answered, right answer was accepted
Array index is out of range
Hello all! I'm working on a 2D sprite-based game, writing code to make sure overlapping multiplayer sprites look proper. I'm doing this by checking the y values of the four players and changing the sprites layers accordingly - held in four arrays under sprites
, however I keep getting the Array index is out of range
error (location marked in my code) for sprites[i].Length
,valueCheck[i]==0
and sprites[i][j].sortingLayerName =
. I've double checked to make sure that there is actually content in my arrays and it seems all fine there (the secondary arrays of sprites
are different lengths if that affects anything). Anyone able to help me figure what's causing my problem?
public GameObject[] players;
public SpriteRenderer[][] sprites;
public int[] valueCheck;
void Start(){
sprites = new SpriteRenderer[4][];
valueCheck = new int[4];
for (int i = 0; i < players.Length; i++) {
sprites[i] = players[i].GetComponentsInChildren<SpriteRenderer>(true);
}
}
void Update() {
for (int i = 0; i < players.Length; i++) {
valueCheck[i] = 0;
}
for (int i = 0; i < players.Length; i++) {
for (int j = 0; j < players.Length; j++) {
if (players[i].transform.position.y > players[j].transform.position.y) {
valueCheck[i]++;
}
}
}
for (int i = 0; i < players.Length; i++) {
//this is the error point
for (int j = 0; j < sprites[i].Length; i++) {
if (valueCheck[i] == 0)
sprites[i][j].sortingLayerName = "Bottom";
if (valueCheck[i] == 1)
sprites[i][j].sortingLayerName = "Low";
if (valueCheck[i] == 2)
sprites[i][j].sortingLayerName = "High";
if (valueCheck[i] == 3)
sprites[i][j].sortingLayerName = "Top";
}
}
}
Follow this Question
Related Questions
IndexOutofRangeException 1 Answer
Index out of Range Exception Error 2 Answers
IndexOutOfRangeException in build but not editor 0 Answers
IndexOutOfRangeException help on debug 3 Answers
Add to Array 1 Answer