Customize how Unity creates tiles from a texture
To customize how Unity creates tiles from a texture, create a script that inherits from TileTemplate.
Read time 2 minutesLast updated 23 days ago
To customize how Unity creates tiles from a texture, create a script that inherits from .
TileTemplateFollow these steps:
-
In the Project window, create a folder called Editor.
-
To create a new C# script, right-click the Editor folder then select Create > MonoBehaviour script.
-
Open the script and replace the code with a class that inherits from. For example:
UnityEngine.Tilemaps.TileTemplateusing System.Collections.Generic;using UnityEngine;using UnityEngine.Tilemaps;public class MyTileTemplate : TileTemplate{} -
Implement themethod. This method provides you with the source texture and its sprites, so you can write code that creates and places tiles in the tile palette.
CreateTileAssetsFor example, the following code creates a single row of tiles in the tile palette from the sprites in the source texture:public override void CreateTileAssets(Texture2D texture2D, IEnumerable<Sprite> sprites, ref List<TileChangeData> tilesToAdd){ int xTilePosition = 0; // For each sprite in the source texture foreach (Sprite sprite in sprites) { // Create a new tile instance and assign the sprite Tile newTile = ScriptableObject.CreateInstance<Tile>(); newTile.name = sprite.name; newTile.sprite = sprite; // Position the tile at the current X position in the tile palette tilesToAdd.Add(new TileChangeData() { position = new Vector3Int(xTilePosition, 0, 0), tile = newTile, transform = Matrix4x4.identity, color = Color.white }); // Increment the x position for the next tile xTilePosition++; }} -
To create instances of the tile template in your project, add aattribute before the class declaration.
CreateAssetMenu[CreateAssetMenu]public class MyTileTemplate : TileTemplate{ // ...} -
Create an instance of the tile template in the Project window. For example in the previous example, from the main menu, select Assets > Create then the name of yourclass.
TileTemplate -
After you add a texture to the tileset, drag the tile template asset from the Project window to the Tile Template field in the Tile Set Importer Inspector window.
-
Select Apply, then open the Tile Palette Window to check the tiles created by your tile template.