Unity中如何获取指定Tile的周围相邻瓦片?
实现方案
你可以通过预定义相邻瓦片的坐标偏移量,遍历计算所有相邻位置的网格坐标后获取对应瓦片,修改后的代码如下:
public List<TileBase> FindAllTileNeighbors(Vector2 gameObjectPosition){ // 初始化返回列表,避免空引用异常 List<TileBase> sTiles = new List<TileBase>(); GridLayout grid = map.GetComponentInParent<GridLayout>(); Vector3Int gridPosition = grid.WorldToCell(gameObjectPosition); // 定义8邻域的坐标偏移量,若只需要上下左右4邻域可删除斜向偏移项 Vector3Int[] neighborOffsets = new Vector3Int[] { new(-1, 1, 0), // 左上 new(0, 1, 0), // 正上 new(1, 1, 0), // 右上 new(-1, 0, 0), // 正左 new(1, 0, 0), // 正右 new(-1, -1, 0), // 左下 new(0, -1, 0), // 正下 new(1, -1, 0) // 右下 }; foreach (var offset in neighborOffsets) { Vector3Int neighborPos = gridPosition + offset; // 可选:判断坐标是否在Tilemap有效范围内,避免越界查询 if (map.cellBounds.Contains(neighborPos)) { TileBase neighborTile = map.GetTile(neighborPos); // 若需要收录空瓦片可删除该判断条件 if (neighborTile != null) { sTiles.Add(neighborTile); } } } return sTiles; }
注意事项
- 代码默认使用8邻域规则获取所有相邻瓦片,若只需上下左右4个正方向相邻瓦片,删除
neighborOffsets数组中4个斜向偏移项即可 - 若你的项目使用的是带Z轴分层的3D瓦片网格,根据实际分层规则调整偏移量的Z轴参数即可
- 已默认添加越界校验逻辑,避免查询Tilemap范围外的无效坐标
内容的提问来源于stack exchange,提问作者egurb
相关产品推荐
相关产品推荐

