到目前为止,我可以从我的文本文件中读取。然后我继续尝试访问每一行。从这里我尝试访问行中的每个值。如果它是 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++;
}
关于c# - 尝试统一使用 C# 从文本文件生成迷宫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29172613/