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

如何获取地牢房间预制件地板的Vector2Int尺寸?

获取地牢房间Prefab地板的Vector2Int尺寸

以下是两种常见场景的解决方案,根据你的地板实现方式选择:


场景1:地板由多个独立Tile GameObject组成

如果你的地板是层级里一个个独立的Tile子物体(对应你提到的第二张截图),可以用以下代码计算组合后的尺寸:

  1. 给所有地板Tile统一加个标签(比如FloorTile),方便精准筛选
  2. 在房间根物体上挂载这个脚本,拖拽地板Tile的父物体到对应字段:
using UnityEngine;
using System.Collections.Generic;

public class FloorSizeGetter : MonoBehaviour
{
    [SerializeField] private Transform _floorTilesParent;

    public Vector2Int GetFloorDimensions()
    {
        if (_floorTilesParent == null)
        {
            Debug.LogError("未指定地板Tile的父物体!");
            return Vector2Int.zero;
        }

        var floorTiles = new List<Transform>();
        foreach (Transform child in _floorTilesParent)
        {
            if (child.CompareTag("FloorTile"))
                floorTiles.Add(child);
        }

        if (floorTiles.Count == 0)
        {
            Debug.LogError("未找到任何地板Tile!");
            return Vector2Int.zero;
        }

        float minX = float.MaxValue;
        float maxX = float.MinValue;
        float minY = float.MaxValue;
        float maxY = float.MinValue;

        foreach (var tile in floorTiles)
        {
            var pos = tile.position;
            minX = Mathf.Min(minX, pos.x);
            maxX = Mathf.Max(maxX, pos.x);
            minY = Mathf.Min(minY, pos.y);
            maxY = Mathf.Max(maxY, pos.y);
        }

        // 假设Tile按整数网格排列,取整后加1(包含首尾Tile的尺寸)
        int width = Mathf.RoundToInt(maxX - minX) + 1;
        int height = Mathf.RoundToInt(maxY - minY) + 1;

        return new Vector2Int(width, height);
    }

    // 编辑器里右键点击脚本组件,选择"计算地板尺寸"即可查看结果
    [ContextMenu("计算地板尺寸")]
    private void LogFloorSize()
    {
        var size = GetFloorDimensions();
        Debug.Log($"地板组合尺寸:{size.x} × {size.y}");
    }
}

场景2:地板用Unity Tilemap实现

如果你的地板是用Tilemap系统制作的,直接获取Tilemap的内置属性即可:

using UnityEngine;
using UnityEngine.Tilemaps;

public class TilemapSizeGetter : MonoBehaviour
{
    [SerializeField] private Tilemap _floorTilemap;

    public Vector2Int GetFloorDimensions()
    {
        if (_floorTilemap == null)
        {
            Debug.LogError("未指定地板Tilemap!");
            return Vector2Int.zero;
        }

        var size = _floorTilemap.size;
        return new Vector2Int(size.x, size.y);
    }

    [ContextMenu("计算地板尺寸")]
    private void LogFloorSize()
    {
        var size = GetFloorDimensions();
        Debug.Log($"地板尺寸:{size.x} × {size.y}");
    }
}

注意事项

  • 如果Tile坐标不是整数对齐的,需要调整取整逻辑(比如用Mathf.Floor或Mathf.Ceil替代RoundToInt)
  • 确保只筛选真正的地板Tile,避免把墙壁、装饰等无关物体算入结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 04:00:46