Tiles created with SetTile, not rendering when game is running

I have four tilemaps in my 2D URP project:

Ground, Walls, Path, Selection

They have their own ordering (0, 1, 2, 3 respectively).

Now when a user mouse overs a grid, I want to draw a highlight tile on the Selection tilemap.

I wrote this code:

public class GridController  : MonoBehaviour
{
    [SerializeField] Tilemap selectionHighlights;
    [SerializeField] Tile selectionTile;

    private Grid grid;
    // Start is called before the first frame update
    void Start()
    {
        grid = GetComponent<Grid>();
    }

    Vector3Int GetMousePosition()
    {
        Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        return grid.WorldToCell(mouseWorldPos);
    }

    // Update is called once per frame
    void Update()
    {
        var mousePos = GetMousePosition();
        if (Input.GetMouseButtonDown(0))
        {
            Debug.Log("Mouse position over " + mousePos.x + "/" + mousePos.y);
            selectionHighlights.SetTile(mousePos, selectionTile);
        }
    }
}

When I run the game, nothing happens. I see the log message, but not the tile being created.

If I PAUSE the game, the tiles I created are visible. If I continue playing the game, the tiles disappear.

I’m not sure what I’m doing wrong, anyone have a clue?

Well, by setting my Camera’s far clipping plane to 0, instead of 0.3, this seemed to resolve the issue. I can’t say why it did though, since I’m still fairly new to Unity. Perhaps someone who reads this could elucidate further?

1 Like

One way I’ve had things go wrong is this line:

Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

What happens here is that the camera’s z position is preserved, which is often -10. That may not be visible to the camera.

Add this: mouseWorldPos.z = 0f;

That is good practice in general because you likely don’t want to set your tiles to (x, y, -10) accidentally.

Oh man, you are a savior :heart:
The clipping was the problem for me as well. I was experimenting with this simple code.
Sorry for necroposting, but anyone that comes across the same problem, use this and set the camera clipping planes to 0.

public TileBase tile;
    public Tilemap map;
    public Camera cam;

    private void Update()
    {
        Vector3Int newPos = map.WorldToCell(cam.ScreenToWorldPoint(Input.mousePosition));
        if (Input.GetMouseButton(0)) {
            DrawTile(newPos);
        }
    }

    void DrawTile(Vector3Int position)
    {
        print(position);
        map.SetTile(position, tile);
    }