c# - 尝试统一使用 C# 从文本文件生成迷宫

标签 c# unity3d char

到目前为止,我可以从我的文本文件中读取。然后我继续尝试访问每一行。从这里我尝试访问行中的每个值。如果它是 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/

相关文章:

C char函数(void)和void函数(void)的区别

c# - 将字符串转换为命令?

java - 如何计算用户输入中的字符、字母、空格

c# - Controller 上的 ExecuteCore/Execute/Initialize 有何不同?

c# - EF4 代码仅映射继承

c# - 如何使用回调字符串到主窗体

c# - 有没有一种方法可以为一个接口(interface)编写测试,然后针对所有实现该测试的类对其进行测试?

c# - 如何使 Sprite 颜色取决于 HP 变量? (hp 越少,红色 Sprite 应该越多)

c# - 无法将文件/图像设置为对象跟踪器的 RunTimeImageSource

c - 为什么字符串终止不会发生在空字符处