首页 > 解决方案 > 如何找到所有空图块并在其中实例化对象?

问题描述

我在 Unity 中使用 Tilemaps 创建了一个“PacMan”地图,但我以前从未使用过它们,所以我想知道,如何在代码中找到我的地图上的所有空图块并在其中生成对象?

我的地图

标签: c#unity3d2dtile

解决方案


我在网上找到了这个来获取瓷砖空间:

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变量设置为带有瓦片地图组件的游戏对象。

让我知道是否有任何错误


推荐阅读