[英]Trying to produce a maze from a text file using c# in unity
到目前为止,我能够从我的文本文件中读取。 然后我继续尝试访问每一行。 从这里我尝试访问该行中的每个值。 如果它是1,我将在位置x = 1处创建一个游戏对象,如果下一个是1则该对象将位置位置x = 2.一旦读取该行,我想从y = 0改变位置(第一行)到y = 1,依此类推。
我的问题是,当我尝试运行时,我似乎只从每一行获得第一个值。 有人可以查看我的代码并告诉我我的脑筋在哪里吗? 我将不胜感激 :)!
//Splits each line to be accessed easily
eachLine = File.ReadAllLines("Maze1.txt");
//Gets number of lines
int lines = File.ReadAllLines("Maze1.txt").Length;
// Accesses each line one at a time
foreach (string line in eachLine)
{
// Accessess each character in each line one at a time
foreach(char c in line)
{
string currentNum = c.ToString();
thisNum = Convert.ToInt32(currentNum);
//Console.WriteLine("This Number: {0}",thisNum)
if (thisNum != 1)
{
//While i
while(i < lines)
{
ObjectSpawnPosition = new Vector3(i+1,0,0);
Console.WriteLine("This num is 1");
Instantiate(obj, ObjectSpawnPosition, Quaternion.identity);
i++;
}
}
你的问题是你如何循环。 如果读取1,则循环遍历线并为每一行创建一个对象。 相反,你应该这样做:
int y = 0;
// Accesses each line one at a time
foreach (string line in eachLine)
{
// reset the x position to the beginning of each line.
int x = 0;
// Accesses each character in each line one at a time
foreach(char c in line)
{
string currentNum = c.ToString();
thisNum = Convert.ToInt32(currentNum);
if (thisNum == 1)
{
// Create a single object at x,y (no looping here)
ObjectSpawnPosition = new Vector3(x,y,0);
Instantiate(obj, ObjectSpawnPosition, Quaternion.identity);
}
// increment x inside the inner loop.
x++;
}
// done with a line, so increment y to go to the next line.
y++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.