如何解决如何找到所有空瓷砖并在其中实例化对象?
我使用 Tilemaps 在 Unity 中创建了一个“吃豆人”地图,但我以前从未使用过它们,所以我想知道,如何在我的地图上用代码找到所有空图块并在其中生成对象?
解决方法
我在网上找到了这个来获取平铺空间:
using UnityEngine;
using UnityEngine.Tilemaps;
public class TileTest : MonoBehaviour {
void Start () {
Tilemap tilemap = GetComponent<Tilemap>();
BoundsInt bounds = tilemap.cellBounds;
TileBase[] allTiles = tilemap.GetTilesBlock(bounds);
for (int x = 0; x < bounds.size.x; x++) {
for (int y = 0; y < bounds.size.y; y++) {
TileBase tile = allTiles[x + y * bounds.size.x];
if (tile != null) {
Debug.Log("x:" + x + " y:" + y + " tile:" + tile.name);
} else {
Debug.Log("x:" + x + " y:" + y + " tile: (null)");
}
}
}
}
}
我想你可以把它改成这样的东西来获得所有的空白空间:(这个脚本必须附加到带有瓷砖地图组件的游戏对象)
using UnityEngine;
using UnityEngine.Tilemaps;
using System.Collections.Generic;
using System;
public class TileTest : MonoBehaviour {
Vector3[] emptyCells;
void Start () {
List<Vector3> empty = new List<Vector3>();
Tilemap tilemap = GetComponent<Tilemap>();
BoundsInt bounds = tilemap.cellBounds;
TileBase[] allTiles = tilemap.GetTilesBlock(bounds);
for (int x = 0; x < bounds.size.x; x++) {
for (int y = 0; y < bounds.size.y; y++) {
TileBase tile = allTiles[x + y * bounds.size.x];
if (tile == null) {
empty.Add(new Vector3(x,y,0f));
Debug.Log("x:" + x + " y:" + y);
}
}
}
emptyCells = empty.ToArray();
}
}
通过这种方式,您可以访问 emptyCells
数组,并获取生成对象的位置。
此脚本仅在您将其附加到具有 tile 地图组件的同一游戏对象时才有效。如果您不想这样,请将脚本的第一部分更改为:
using UnityEngine;
using UnityEngine.Tilemaps;
using System.Collections.Generic;
using System;
public class TileTest : MonoBehaviour {
public GameObject obj;
Vector3[] emptyCells;
void Start () {
List<Vector3> empty = new List<Vector3>();
Tilemap tilemap = obj.GetComponent<Tilemap>();
...
确保将 obj
变量设置为具有图块地图组件的游戏对象。
如果有任何错误请告诉我
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。