[英]create grid by reading from external file in Unity
創建網格時,我通常會去
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();
}
}
但我想從外部文本文件中讀取地圖信息。 單元格本身具有此構造函數
public Cell(Celltype type = null, Enemy enemy = null)
我想創建一個文本文件語法來讀取它。
這是示例行
[(火)(霜凍,地精)()]
Unity文檔提供了一個TextAsset
https://docs.unity3d.com/Manual/class-TextAsset.html
我嘗試以此方式讀取文件
private void ReadFile(string fileToRead)
{
TextAsset txt = Resources.Load("Maps/" + fileToRead) as TextAsset;
string content = txt.text;
}
但這只是返回全文。 我想用四個不同的行創建此示例地圖
[(forest,dragon)()] ->兩個單元格,第一個包含元素和敵人,第二個為空
[(frost,dragon)()()(frost,yeti)] ->四個單元格,2和3為空
[(死亡,巨人)(火,地精)] ->兩個帶有元素和敵人的牢房
[()()()()()()] ->六個空單元格
創建地圖時,如何在我的代碼中獲取文本信息? 也許對於外部文件有更好的語法?
您應該解析結果字符串( content
)。 請注意,創建自己的格式可能不是一個好主意,因為您必須自己編寫解析器。 考慮使用現有的標記語言,例如XML或JSON。
這是您的示例在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": [{}, {}, {}, {}, {}, {}]}
]
}
如果將此JSON存儲在字符串中,則可以使用例如Json.NET庫從此字符串創建一個對象。
我個人會使用JSON,但是如果您不想使用第三方庫,請知道.NET API已經存在與XML相關的類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.