简体   繁体   中英

create grid by reading from external file in Unity

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.

  • [] means a new row
  • () means one cell in a row

this is an example row

[(fire)(frost, goblin)()]

  • The first cell would be a cell of type fire. This cell has no enemy on it.
  • The second cell would be a cell of type frost. This cell has a goblin on it.
  • The third cell has no type and no enemy.

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM