Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Tiles created with SetTile, not rendering when game is running

Discussion in '2D' started by mookfist, Jun 15, 2022.

  1. mookfist

    mookfist

    Joined:
    Jun 12, 2022
    Posts:
    2
    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:

    Code (CSharp):
    1.    
    2. public class GridController  : MonoBehaviour
    3. {
    4.     [SerializeField] Tilemap selectionHighlights;
    5.     [SerializeField] Tile selectionTile;
    6.  
    7.     private Grid grid;
    8.     // Start is called before the first frame update
    9.     void Start()
    10.     {
    11.         grid = GetComponent<Grid>();
    12.     }
    13.  
    14.     Vector3Int GetMousePosition()
    15.     {
    16.         Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    17.         return grid.WorldToCell(mouseWorldPos);
    18.     }
    19.  
    20.     // Update is called once per frame
    21.     void Update()
    22.     {
    23.         var mousePos = GetMousePosition();
    24.         if (Input.GetMouseButtonDown(0))
    25.         {
    26.             Debug.Log("Mouse position over " + mousePos.x + "/" + mousePos.y);
    27.             selectionHighlights.SetTile(mousePos, selectionTile);
    28.         }
    29.     }
    30. }
    31.  
    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?
     
  2. mookfist

    mookfist

    Joined:
    Jun 12, 2022
    Posts:
    2
    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?
     
  3. Lo-renzo

    Lo-renzo

    Joined:
    Apr 8, 2018
    Posts:
    1,323
    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.