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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

How to detect painting/change to tilemap

Discussion in '2D' started by theGreatSlutze, Nov 23, 2019.

  1. theGreatSlutze

    theGreatSlutze

    Joined:
    Jan 7, 2013
    Posts:
    25
    I’d like to be able to execute a function when any of my tilemaps is painted on, but I’m not sure what the right way to do that is. Ideally I would be able to tell which tilemap was painted on, and what cell had changed. Should I be trying to achieve this with a custom brush, or some other way?
     
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    @theGreatSlutze

    I guess you could first detect the object selection change in your editor script:

    https://docs.unity3d.com/ScriptReference/Selection-selectionChanged.html

    Then selection has activeObject which you can use to detect if you have a tilemap selected.

    Then there is also Event for editor windows, so if selection gets changed, this method in window gets called.

    https://docs.unity3d.com/ScriptReference/EditorWindow.OnSelectionChange.html

    And to get position, you can use Tilemap / Grid related helpers, something like this:
    Code (CSharp):
    1. void GetSelectedTile()
    2. {
    3.     if (tilemap == null)
    4.         return;
    5.  
    6.     if (Selection.activeObject != null)
    7.     {
    8.         var gridSel = GridSelection.active;
    9.  
    10.         if (gridSel)
    11.         {
    12.             pos = GridSelection.position;
    13.             tile = tilemap.GetTile(pos.position);
    14.         }
    15.     }
    16. }
     
    Last edited: Nov 23, 2019
  3. theGreatSlutze

    theGreatSlutze

    Joined:
    Jan 7, 2013
    Posts:
    25
    Does the object selection change when you paint a tile? I wouldn’t have thought it would change since the tilemap is all a single object.
     
  4. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    I guess probably not but you could figure it out.

    When selection changes, I would check if and what tilemap I have or not.

    When the grid selection is active, some tilemap must be selected, and grid selection also contains position, so you know what tile map is being painted, and you know the exact coordinate, then you can get the cell and its tile... you could track yourself if tile selection / cell has changed since last editor script update.