Hi Internet, I’m already developing my 2d game but the problem is editing the tile map. You See, the method used for Tilemaps to edit a tile is SetTile(Vector3Int pos, Tilebase tile), but how do I add a tile if the position I pressed has no Tile?
Here is my Code:
public class TerrainEditManager : MonoBehaviour
{
public PlayerMovement move;
public TileBase currentTile;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
CastRay();
}
}
void CastRay()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity);
if (hit.collider != null)
{
Tilemap map = hit.collider.gameObject.GetComponent<Tilemap>();
if (map != null)
{
Vector3Int cell = map.WorldToCell(hit.point);
if (!((move.movingJoystick.Horizontal >= 0.01 || move.movingJoystick.Horizontal <= -0.01)|| (move.otherJoystick.Vertical >= 0.01 || move.otherJoystick.Vertical <= -0.01)))
{
TileBase tileBase = map.GetTile(cell);
Sprite sprite = map.GetSprite(cell);
if (tileBase != null)
{
StartCoroutine(DeleteTile(map, cell, GetTileDuration(sprite.name)));
Debug.Log("Yay");
}
else
{
map.SetTile(cell, currentTile);
Debug.Log("No");
}
}
}
else
{
Debug.Log("No");
}
}
}
public IEnumerator DeleteTile(Tilemap tilemap, Vector3Int pos, float duration)
{
yield return new WaitForSeconds(duration);
tilemap.SetTile(pos, null);
}
public float GetTileDuration(string tileName)
{
switch (tileName)
{
default: return 0f;
case "Tile 1": return 1f;
case "Tile 2": return 0.5f;
case "Tile 3": return 2f;
}
}
}
Please I need a solution quick cause this is a challenge to prove myself. Thanks for the Answers.