I have want to make the levels in my game load from a textfile and load it into a 2d array, this is what the level textfile looks:
0,0,0,0,0,0,0,0,0,0
1,1,1,1,1,1,1,1,1,1
2,2,2,2,2,2,2,2,2,2
3,3,3,3,3,3,3,3,3,3
4,4,4,4,4,4,4,4,4,4
5,5,5,5,5,5,5,5,5,5
6,6,6,6,6,6,6,6,6,6
7,7,7,7,7,7,7,7,7,7
8,8,8,8,8,8,8,8,8,8
9,9,9,9,9,9,9,9,9,9
I want each number to be a seperate tile ingame, the commas would act as a seperator, but I have no idea how to actually get the data out of this into my 2d array. This is how far I've got:
Tile[,] Tiles;
string[] mapData;
public void LoadMap(string path)
{
if (File.Exists(path))
{
mapData = File.ReadAllLines(path);
var width = mapData[0].Length;
var height = mapData.Length;
Tiles = new Tile[width, height];
using (StreamReader reader = new StreamReader(path))
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
Tiles[x, y] = new Tile(SpriteSheet, 5, 3, new Vector2(x * 64, y * 64));
}
}
}
}
}
The numbers 5 and 3 in the line Tiles[x, y] = new Tile() represent the position of the texture in the textureatlas. I want to add an if statement like if the number in the file is 0 at the topleft, I want Tiles[0, 0] to set to a specific row and column in my textureatlas. Any help on this would be greatly appreciated, I'm not seeing it!
First, var width = mapData[0].Length;
is going to return the length of the character array, including the commas, which is 19. It looks like you do not want it to return commas. So, you should split the string like so:
Tile[,] Tiles;
string[] mapData;
public void LoadMap(string path)
{
if (File.Exists(path))
{
mapData = File.ReadAllLines(path);
var width = mapData[0].Split(',').Length;
var height = mapData.Length;
Tiles = new Tile[width, height];
using (StreamReader reader = new StreamReader(path))
{
for (int y = 0; y < height; y++)
{
string[] charArray = mapData[y].Split(',');
for (int x = 0; x < charArray.Length; x++)
{
int value = int.Parse(charArray[x]);
...
Tiles[x, y] = new Tile(SpriteSheet, 5, 3, new Vector2(x * 64, y * 64));
}
}
}
}
}