r/Unity2D • • 4d ago

Question/Help Storing data on individual tiles?

I have a proc gen tilemap system and I need each tile to have it's own copy of a script to be able to pull and assign data to. All the tiles are rule tiles, idk if that makes a difference. How would I do that?

1 Upvotes

3 comments sorted by

•

u/AutoModerator 4d ago

Reminder: Once your issue has been resolved, please reply !solved to this comment (or comment it anywhere in the thread) and your post's flair will automatically be updated to Solved/Answered. You can also edit it to Solved/Answered yourself.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

3

u/One_Yam4643 3d ago

Tiles on a Tilemap aren't GameObjects, so there's nothing per cell to hang a script on. A RuleTile is one shared asset that every cell points to, so anything stored on it is shared by all of them.

The usual fix is to keep the data next to the tilemap instead of in it: a Dictionary<Vector3Int, CellData> where the key is the cell position and CellData is a plain C# class (not a MonoBehaviour) holding whatever you need: health, moisture, owner and so on. Your map is proc gen, so you already loop over every cell when you call SetTile; add the dictionary entry in that same loop. To find a tile from the world (mouse, player feet), tilemap.WorldToCell(worldPos) gives you the key.

There is a second way: a RuleTile can spawn a prefab on its cells. Each tiling rule has its own GameObject field; Default GameObject only covers cells where no rule matches, and pre-fills rules you add later. You get the spawned object back with tilemap.GetInstantiatedObject(cell). That gives a real script per tile, but it is one GameObject per cell, so it gets heavy fast on a big generated map. Fine for a few special tiles like chests or doors, not for the whole ground.

What kind of data is it? If it's the same for every tile of a type (walk speed, damage), it can live on a small RuleTile subclass and you don't need per-cell storage at all.

1

u/Federal-Row2373 3d ago

One thing to watch with the Dictionary approach: Unity doesn't serialize dictionaries, so the data won't show in the Inspector or survive a save on its own. If the map needs to be saved and loaded, it's easier to keep a list of cell position plus data and rebuild the dictionary on load, or just regenerate from the same seed and only save the cells that changed. Does the per-tile data need to persist between play sessions?