首页 > 解决方案 > C#世界平铺地图生成器问题

问题描述

我正在开发一款包含 1000 x 1000 方形平铺地图的游戏,但我遇到了问题。

我尝试制作两个不同的脚本来解决这个问题。第一个是我需要的草率方法。我的第二个脚本是一种更有效的方法来满足我的需要。

脚本 1:

 void fill()
    {
        for (float i = 0; i != 1000; i++)
        {
            Instantiate(GameObject.Find("Dirt"), new Vector2(xPos++, yPos), Quaternion.identity);
            xrepeat++;
            if (xrepeat == 1000)
            {
                xPos = 0;
                yPos = yPos - 1;
                yrepeat++;
                if(yrepeat != 1000)
                {
                    i = 0;
                    xPos = 0;
                }
                if(xPos < 0) //Prevents an overflow.
                {
                    break;
                }
            }
        }

脚本 2:

    void buildx()
    {
        for (int i = 1000; i != 0; i--)
        {
            Instantiate(GameObject.Find("Dirt"), new Vector2(xPos++, yPos), Quaternion.identity);
            if (xPos == 1000)
            {
                buildy();
            }
        }
    }
    void buildy()
    {
        if (yPos == -1000)
        {
            Destroy(this); // Job is done, time to pack up
        }
        else
        {
            for (int i = 1000; i != 0; i--)
            {
                Instantiate(GameObject.Find("Dirt"), new Vector2(xPos, yPos--), Quaternion.identity);
                buildx();
            }
        }
    }

第一个脚本将我的污垢块复制了 1000 次,然后将 y 轴减去 1 并重复直到达到配额。那种工作,但它在工作结束时放弃了。第二个脚本在 x 轴和 y 轴之间来回反复检查 1000 个配额,但由于某种原因它冻结了。

我几乎放弃了脚本 1 转而支持脚本 2,因为我认为脚本 2 更有效。

有什么办法可以让脚本 2 工作吗?

标签: c#unity3d

解决方案


我强烈建议您研究 Unity 的工作系统,但是您的循环非常混乱,不知道那里发生了什么……看来您已经使这个复杂化了。所以如果我必须全部实例化它们,这就是我将如何实例化 1000x1000 瓦片的地图:

public int mapWidth = 30;
public int mapHeight = 30;

void fill()
{
    // Doing this once at the beginning, so it isn't super expensive...
    GameObject basePrefab = GameObject.Find("Dirt"); 
    // Creating 1 Vector3 that we can just update the values on
    Vector3 spawnPosition = Vector3.zero;

    for(int x = 0; x < mapWidth; ++x)
    {
        // Update the spawn x Position
        spawnPosition.x = x;
        for(int y = mapHeight; y > 0; y--)
        {
            // Update the spawn y position
            spawnPosition.y = y;
            Instantiate(basePrefab, spawnPosition, Quaternion.identity);
        }
    } 
}

如果您想阅读或查看类似系统的瓦片地图的对象池示例,这是我前段时间写的一个答案,应该会给您它的精神:创建和渲染大量 2d 的最快方法是什么Unity中的精灵?


推荐阅读