Documentation

Unity Engine


User Manual

Script Reference

Unity Engine


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
TileTemplate
.
Note
TileTemplate
only works when you automatically create a tile palette using a tileset, not when you create your own tile palette. For more information, refer to Create a tileset.
Follow these steps:
  1. In the Project window, create a folder called Editor.
  2. To create a new C# script, right-click the Editor folder then select Create > MonoBehaviour script.
  3. Open the script and replace the code with a class that inherits from
    UnityEngine.Tilemaps.TileTemplate
    . For example:
    using System.Collections.Generic;using UnityEngine;using UnityEngine.Tilemaps;public class MyTileTemplate : TileTemplate{}
  4. Implement the
    CreateTileAssets
    method. 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.
    For 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++; }}
  5. To create instances of the tile template in your project, add a
    CreateAssetMenu
    attribute before the class declaration.
    [CreateAssetMenu]public class MyTileTemplate : TileTemplate{ // ...}
  6. 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 your
    TileTemplate
    class.
  7. 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.
  8. Select Apply, then open the Tile Palette Window to check the tiles created by your tile template.

Additional resources