Home > database >  Get size of floor tiles
Get size of floor tiles

Time:01-16

I have a prefab for a dungeon room. How can I get the Vector2Int size of the floor of this room? As you can see in the Hierarchy, I have a transform object with many children. I am only interested in the x and y dimensions of the combined floor tiles, as shown in the second screenshot. enter image description here

enter image description here

CodePudding user response:

  1. It would be useful to have a reference to the floor tiles in your script.

One way to do this is to place the tiles under an empty GameObject and have a reference to the Transform of this GameObject in your script.

public Transform FloorRoot;
  1. Then you need to find the dimensions you're looking for.

If each tile has the same size then you could calculate the combined size with some logic but it's simpler to use the Bounds property of each MeshRenderer of each tile.

Note: This won't work if your floor isn't aligned to the axis (if it is rotated).

The final script could look like this:

public class FloorDimensions : MonoBehaviour
{
    public Transform FloorRoot; // Fill this from the inspector
    private MeshRenderer[] _tilesMeshRenderers;

    private void Awake()
    {
        _tilesMeshRenderers = FloorRoot.GetComponentsInChildren<MeshRenderer>();
    }

    private Vector2 CalculateFloorDimensions()
    {
        Bounds combinedBounds;

        foreach (var renderer in _tilesMeshRenderers)
        {
            combinedBounds.Encapsulate(renderer.bounds);
        }

        // I assume you want the X and Z, not the Y (height).
        return new Vector2(combinedBounds.size.x, combinedBounds.size.z);
    }
}
  • Related