Reputation: 1590
when creating a grid I normally go for
private Cell[,] mapCells = new Cell[10, 10];
for (int x = 0; x < mapSizeHorizontal; x++)
{
for (int y = 0; y < mapSizeVertical; y++)
{
mapCells[x, y] = new Cell();
}
}
but I want to read the map information from a external text file. The cell itself has this constructor
public Cell(Celltype type = null, Enemy enemy = null)
and I thought about creating a text file syntax to read it.
this is an example row
[(fire)(frost, goblin)()]
The Unity docs provide a TextAsset
https://docs.unity3d.com/Manual/class-TextAsset.html
I tried reading the file this way
private void ReadFile(string fileToRead)
{
TextAsset txt = Resources.Load("Maps/" + fileToRead) as TextAsset;
string content = txt.text;
}
but this just returns me the full plain text. I want to create this example map with four different rows
[(forest, dragon)()] -> two cells, first with element and enemy, second is empty
[(frost, dragon)()()(frost, yeti)] -> four cells, 2 and 3 is empty
[(death, giant)(fire, goblin)] -> two cells with element and enemy
[()()()()()()] -> six empty cells
How can I get the text information into my code when creating the map? Maybe there is a better syntax for external files?
Upvotes: 0
Views: 325
Reputation: 1096
You should parse the resulting string (content
). Note that creating your own format is probably a bad idea since you would have to write the parser yourself. Consider using an already existing markup language, like XML or JSON.
Here is what your example would look like in JSON:
{
"level": [
{"row": [{"type": "forest", "monster": "dragon"}, {}]},
{"row": [{"type": "forest", "monster": "dragon"}, {}, {}, {"type": "frost", "monster": "yeti"}]},
{"row": [{"type": "death", "monster": "giant"}, {"type": "fire", "monster": "goblin"}]},
{"row": [{}, {}, {}, {}, {}, {}]}
]
}
If this JSON is stored into a string, you can then create an object from this string using for example the Json.NET library.
I would personally use JSON but if you do not want to use a third-party library, know that the .NET API has already existing XML related classes.
Upvotes: 3