c# - 如何找到所有空图块并在其中实例化对象?
解决方案
我在网上找到了这个来获取瓷砖空间:
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
数组,并获取生成对象的位置。
此脚本仅在您将其附加到与瓦片地图组件相同的游戏对象时才有效。如果您不想这样,请将脚本的第一部分更改为:
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
变量设置为带有瓦片地图组件的游戏对象。
让我知道是否有任何错误
推荐阅读
- c - 关于 C 中结构的一些事情 - 我不明白
- javascript - 重新加载时随机化输入 (HTML) 中的文本 (JS)
- javascript - JS 将列表作为 JS 中的字符串转换为 JSON 格式 - 这可能吗?
- c# - 静态事件 WPF MVVM 的替代方案
- python - 如何在不降低服务器速度的情况下处理多个图像上传?
- java - 如何使用 ApplicationListener ConfigurableApplicationContext 初始化的服务
- audio - 带有音频过滤的 FFmpeg 拆分过滤器会引发错误
- python - 远程:-----> Python 应用检测到远程:!请求的运行时(Python 3.6.4)不适用于此堆栈(heroku-18)
- python - List constructor for async gen
- angular - 带有 asyncValidators 的 ngx-formly:在验证运行时显示一些信息/样式