Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Unity component that is also a Tile in a Tilemap.
using UnityEngine;
using UnityEngine.Tilemaps;
/// <summary>
/// A component that is also a Tile in a Tilemap. If the Tilemap is not
/// specified it will default to the Tilemap in the parent Game Object.
/// </summary>
public class TileComponent : MonoBehaviour
{
public Tilemap tilemap;
Tile tile;
Vector3 curPos;
public virtual void Start()
{
if (tilemap == null)
{
tilemap = GetComponentInParent<Tilemap>();
}
tile = ScriptableObject.CreateInstance<Tile>();
curPos = transform.position;
SetTile(transform.position);
}
/// <summary>
/// Sets a tile representing the game object to the given location in the
/// tilemap. Call this method whenever the game object moves to a new
/// location on the tilemap.
/// </summary>
public void SetTile(Vector3 newPos)
{
tilemap.SetTile(tilemap.WorldToCell(curPos), null);
tilemap.SetTile(tilemap.WorldToCell(newPos), tile);
curPos = newPos;
}
public virtual void OnDestroy()
{
tilemap.SetTile(tilemap.WorldToCell(curPos), null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment