- Home /
Argument out of range exception
What I'm trying to do is look at a list of sprites and make a list out of each pixel in the array. This is most likely a bit confusing, so let me show you my code.
public List<Sprite> img = new List<Sprite>();
public List<List<Color>> color = new List<List<Color>>();
void Start(){
//for every image
for (int a = 0; a < img.Count; a++) {
//for every pixel that image is wide
for (int i = 0; i < img[a].texture.width; i++) {
//for every pixel that image is high
for (int j = 0; j < img[a].texture.height; j++) {
//new color for every pixel of image a
Color pixel = img[a].texture.GetPixel (i, j);
//add all the pixel colors to the list in the color list at index a
//error here
color[a].Add (pixel);
}
}
}
Debug.Log (color.Count);
Debug.Log (color[0].Count);
Debug.Log (color[1].Count);
}
I'm getting an argument out of range exception on line 16, and I'm not sure why. If anyone else does, it would be very much appreciated.
And if it makes anyone feel better, I also wrote this other description of what I want it to do. (sorry its sideways, I don't know how to fix it.)
Answer by MarshallN · Feb 21, 2017 at 05:32 PM
Simple problem - you're calling color[a].Add (pixel), but there's no element [a] in color yet! So what you need to do is add a List for every image. Your script should actually look like this:
public List<Sprite> img = new List<Sprite>();
public List<List<Color>> color = new List<List<Color>>();
void Start(){
//for every image
for (int a = 0; a < img.Count; a++) {
color.Add(new List<Color>()) //THIS IS THE LINE I ADDED
//for every pixel that image is wide
for (int i = 0; i < img[a].texture.width; i++) {
//for every pixel that image is high
for (int j = 0; j < img[a].texture.height; j++) {
//new color for every pixel of image a
Color pixel = img[a].texture.GetPixel (i, j);
//add all the pixel colors to the list in the color list at index a
//error here
color[a].Add (pixel);
}
}
}
Debug.Log (color.Count);
Debug.Log (color[0].Count);
Debug.Log (color[1].Count);
}
Thanks, that makes sense why I was getting the error.
Your answer
Follow this Question
Related Questions
Trouble with removing items from a list by string 0 Answers
Change sprite color on GameObjects from a list. 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
A node in a childnode? 1 Answer