You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity网格式关卡生成器无法触发生成停止逻辑求助

网格式Procedural Level Generator 卡顿在倒数第二行的问题排查与修复

核心问题拆解

生成器卡在倒数第二行来回跳,本质是向下移动的逻辑失效,导致没法触达底部触发stopGeneration。大概率是方向选择、边界判断或越界重置的逻辑出了问题。

针对性修复方案

1. 给向下移动加「优先级buff」

如果随机选方向时,左右方向的概率太高,就容易来回晃。可以在接近底部时强制优先向下:

private Direction GetNextDirection()
{
    List<Direction> possibleDirs = new List<Direction>();
    int bottomRow = gridHeight - 1;

    // 只剩一行到顶时,只允许向下
    if (currentPosition.y == bottomRow - 1)
    {
        possibleDirs.Add(Direction.Down);
    }
    else
    {
        possibleDirs.Add(Direction.Down);
        // 左右方向只在边界内才添加
        if (currentPosition.x > 0) possibleDirs.Add(Direction.Left);
        if (currentPosition.x < gridWidth - 1) possibleDirs.Add(Direction.Right);
    }

    return possibleDirs[Random.Range(0, possibleDirs.Count)];
}

2. 修正越界重置逻辑

别让越界处理把向下的路径堵死,向下越界直接触发停止,只处理左右越界:

private void MoveNext()
{
    Direction nextDir = GetNextDirection();
    Vector2Int newPos = currentPosition;

    switch (nextDir)
    {
        case Direction.Down:
            newPos.y++;
            // 到直接底部触发停止,不用走重置逻辑
            if (newPos.y >= gridHeight)
            {
                stopGeneration = true;
                return;
            }
            break;
        case Direction.Left:
            newPos.x--;
            break;
        case Direction.Right:
            newPos.x++;
            break;
    }

    // 只修正左右越界,向下越界已经提前处理
    if (newPos.x < 0) newPos.x = 0;
    if (newPos.x >= gridWidth) newPos.x = gridWidth - 1;

    currentPosition = newPos;
}

3. 检查stopGeneration的触发条件

别加多余限制,只要触达底部行就触发:

// 错误示例:额外条件卡了触发
// if (currentPosition.y == gridHeight - 1 && someUnnecessaryCondition) stopGeneration = true;

// 正确写法:到了底部就停
if (currentPosition.y >= gridHeight - 1)
{
    stopGeneration = true;
}

4. 加调试输出定位问题

循环里打印当前位置和选的方向,看哪一步卡了:

void Update()
{
    if (!stopGeneration)
    {
        Debug.Log($"当前位置:({currentPosition.x}, {currentPosition.y}),选的方向:{GetNextDirection()}");
        MoveNext();
        // 其他生成逻辑
    }
}

按上面的步骤调,应该能打通向下的路径,顺利触达底部停止生成。

内容的提问来源于stack exchange,提问作者Kristine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 19:58:21