0

I am making a small game in C# and I am trying to load images into an array, but it keeps saying the index is out of range.

Here's the part that is giving me an error:

Image[] Map = new Image[10]; Image map1 = Image.FromFile("_Maps_\\map1.png"); Map[1] = map1; Image map2 = Image.FromFile("_Maps_\\map2.png"); Map[1] = map2; Image map3 = Image.FromFile("_Maps_\\map3.png"); Map[1] = map3; Image map4 = Image.FromFile("_Maps_\\map4.png"); Map[1] = map4; Image map5 = Image.FromFile("_Maps_\\map5.png"); Map[1] = map5; Image map6 = Image.FromFile("_Maps_\\map6.png"); Map[1] = map6; Image map7 = Image.FromFile("_Maps_\\map7.png"); Map[1] = map7; Image map8 = Image.FromFile("_Maps_\\map8.png"); Map[1] = map8; Image map9 = Image.FromFile("_Maps_\\map9.png"); Map[1] = map9; Image map10 = Image.FromFile("_Maps_\\map10.png"); Map[1] = map10; 

I am a bit new to arrays in C#

If you need more code just ask

2
  • 1
    That can't be the actual code that gives the error. You are putting all the images in the same item in the array, so you end up with an array containing the last image and 9 null references, but no error. Commented Jan 10, 2016 at 2:04
  • Oh oops, sorry for waisting your time. I didn't notice that Commented Jan 10, 2016 at 2:05

1 Answer 1

1

There is a easy way to load this images using LINQ, see below:

Image[] Map = Directory.GetFiles("_Maps_", "*.png") .Select(file => Image.FromFile(file)) .ToArray(); 

Using this way you wont care about name of maps, and if you add a new map, it will be taken from this code.

You can simplify this code a little bit

Image[] Map = Directory.GetFiles("_Maps_", "*.png") .Select(Image.FromFile) .ToArray(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.