- Home /
Tilemap Player destroy tile on contact
I am looking for information about how to use the more advanced options on a tile map. What I am trying to find is help with destroying one tile a time from tilemap. The game player is a farmer ploughing a field, a green tile map, as he ploughs the green tile needs to change to brown(mud). Can someone point me in the direction of some tutorial so I can learn how to do this. Would prefer not a youtube video but if that is the only option I will use.
Answer by Statement · May 31, 2021 at 06:14 AM
I fiddled around a little and made this little script. Add it to the tilemap and set Destroyed Tile to the tile you want to be displayed. The Tilemap must have a Tilemap Collider 2D on it as well. Then click the mouse on the tilemap when playing the game to see the effect in action.
using UnityEngine;
using UnityEngine.Tilemaps;
public class TilemapDestroyer : MonoBehaviour
{
// How destroyed tiles should look.
public TileBase destroyedTile;
Tilemap tilemap;
void Start()
{
tilemap = GetComponent<Tilemap>();
}
void Update()
{
if (Input.GetMouseButton(0))
{
// Mouse pos to tile pos
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
Vector3Int pos = tilemap.WorldToCell(hit.point);
// Replace tile with destroyed tile
tilemap.SetTile(pos, destroyedTile);
}
}
}
Your answer
Follow this Question
Related Questions
Replace GameObject with another GameObject and preserve references without using Destroy() 0 Answers
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
SOLVED - String replace % with " in C# 1 Answer
Destructible walls, or objects (etc...) 3 Answers
Pick up objects 2 Answers