Why can't I Set Tile in an Empty space?

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.

You can set tiles to any position possible in a tilemap, however your code raycasts to find out where to place the tile. Raycasts require solid objects in order to find a hit point. Therefore, if the space is empty, the raycast check will fail, and so you can’t place your tile there.


Change your code to use Camera.main.ScreenToWorldPoint(Input.mousePosition). Since this is a 2D game, there is no need for colliders, as it just converts where you click to world space, and places a tile there.