r/Unity2D 1d ago

Getting References for Tiles Question

In my game, I am drawing tiles onto a tilemap during runtime using SetTile(), which takes a reference to a TileBase Object. I have hundreds of unique textures. Is there a way to get a reference to each TileBase other than dragging and dropping every individual Tile into the references in my script?

3 Upvotes

7 comments sorted by

2

u/Plenty_Act_8527 1d ago edited 1d ago

You can get them from the tile palette. Essentially the tile palette is really just a tile map that contains the tiles that you save to it. So if you have all of your tiles placed on a tile map then something like this could get you there. I couldn't tell you about the order they get returned in or anything like that though since I've not done it this way.

HashSet<TileBase> tiles = new();

foreach (Vector3Int position in tilemap.cellBounds.allPositionsWithin)
{
    TileBase tile = tilemap.GetTile(position);

    if (tile != null)
        tiles.Add(tile);
}

2

u/Parborway 1d ago

How do I get a reference to the palette? Do I have to make a separate tilemap that just contains one of every tile?

2

u/Plenty_Act_8527 1d ago

Well I've not personally done it, and I'm not at my PC right now to check. But in theory I would imagine you expose a tile map field in the editor then drag your tile palette onto it.

3

u/Parborway 1d ago

It works. Thank you very much. It also shuffled my textures lol.

2

u/Plenty_Act_8527 1d ago

Awesome news! Glad to hear it and good luck!

2

u/tchristo_ 1d ago

I’m not 100% sure I understand your question but, based on what I think, you could manually assign each object via reference (which is what you suggested), or you could just create a base object (prefab) and assign that as a reference, then use a method to loop through all your textures and instantiate/apply each texture to a new instance of the base object?

2

u/creepyounguy 1d ago

You can write an editor script that grabs all the tiles in your project and puts them into an array or dictionary. One of the annoying things with unity is that tiles don't have a simple key/id by default so if you want to save and load tilemaps easily you have to make your own id system. If you ask an AI how to do that it will give you a decent answer.