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

如何构建支持多层不同Tile Prefab的自定义宽高网格?

实现多层自定义网格的解决方案

首先先修正你原代码里的语法错误,这些错误会导致代码无法正常运行:

  • Void 应该小写为 void
  • for循环的括号后误加分号,破坏循环逻辑
  • y循环的条件错误写成了x < height,应改为y < height
  • Instantiate 语句末尾缺少分号

接下来是多层网格的实现方案,核心思路是在外层增加层循环,为每层分配独立的Tile Prefab,并通过坐标偏移让层与层之间不重叠:

关键改动说明

  • 新增 List<Tile> layerPrefabs 变量,按顺序存储每层对应的Tile Prefab
  • 新增 float layerSpacing 变量,控制层与层之间的间距,避免重叠
  • 外层添加层循环,计算每层的基础偏移坐标,确保层在垂直/前后方向有序排列

完整实现代码

using UnityEngine;
using System.Collections.Generic;

public class GridBuilder : MonoBehaviour
{
    // 单网格的宽高
    public int width = 3;
    public int height = 3;
    // 每层对应的Tile Prefab(列表顺序对应层的堆叠顺序)
    public List<Tile> layerPrefabs;
    // 层与层之间的间距,避免Tile重叠
    public float layerSpacing = 1.2f;

    void BuildGrid()
    {
        // 遍历每一层
        for (int layer = 0; layer < layerPrefabs.Count; layer++)
        {
            Tile currentTilePrefab = layerPrefabs[layer];
            // 计算当前层的垂直偏移:每层向下偏移 height * layerSpacing 的距离
            // 若要前后堆叠,可将Y轴偏移改为Z轴偏移
            float layerOffsetY = -layer * height * layerSpacing;

            // 遍历当前层的X轴
            for (int x = 0; x < width; x++)
            {
                // 遍历当前层的Y轴
                for (int y = 0; y < height; y++)
                {
                    Vector3 tilePosition = new Vector3(x, y + layerOffsetY, 0);
                    Instantiate(currentTilePrefab, tilePosition, Quaternion.identity);
                }
            }
        }
    }

    // 测试用:在启动时生成网格
    void Start()
    {
        BuildGrid();
    }
}

使用说明

  1. 在Unity编辑器中,给layerPrefabs列表添加对应层数的Tile Prefab,比如第0个元素对应X层、第1个对应Y层
  2. 调整layerSpacing参数,让层与层之间的间距适配你的Tile大小
  3. 若需要层在前后方向(Z轴)堆叠,只需将layerOffsetY改为layerOffsetZ,并修改tilePosition的Z值即可

扩展提示

  • 若需要每层宽高不同,可以把width和height改成List<Vector2Int> layerSizes,对应存储每层的宽高数据
  • 可以新增int targetLayerCount变量,配合动态生成的Prefab列表,实现按需创建任意层数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 20:55:09