Search Unity

[TileMap] How to get the Instantiated Object of all tiles ?

Discussion in '2D Experimental Preview' started by Kiupe, Feb 19, 2019.

  1. Kiupe

    Kiupe

    Joined:
    Feb 1, 2013
    Posts:
    528
    Hi,

    Just beginning with Tilemap and I'm struggling how to get the Instantiated object of all tiles. Using TileMap.GetBlocks returns TileBase which does not contains a method to get the Instantiated Object. The GetInstantiatedObject method of TileMap expects a tile coordinate but I don't know how to get all tiles coordinate in order to be able to call that method for all tiles.

    Basically I need to access to all Instantiated Objects and store them in a 2d array that will represent the actual grid. Instantiated objects have a script that initializes values at runtime. So Instantiated object really reflect the grid state.

    Thanks
     
  2. ChuanXin

    ChuanXin

    Unity Technologies

    Joined:
    Apr 7, 2015
    Posts:
    390
    Could you elaborate more on this? This would help a lot!

    Each Tilemap has an origin and a size. If the Tilemap is of a limited size (Tilemap.CompressBounds() can help), you can do the following:

    Code (CSharp):
    1. var bounds = new BoundsInt(tilemap.origin, tilemap.size);
    2. foreach (var position in bounds.allPositionsWithin)
    3. {
    4.     var go = tilemap.GetInstantiatedObject(position);
    5.     // Do action with go here
    6. }
     
  3. Kiupe

    Kiupe

    Joined:
    Feb 1, 2013
    Posts:
    528
    Ok, it all make sense, thanks !
     
  4. sanchitgulati

    sanchitgulati

    Joined:
    Nov 24, 2014
    Posts:
    1
    @ChuanXin Using Unity 2019.3.0f5 and code you suggested returns null for the go variable.
    *Not doing this on Start() call so there is no way values are not initialized yet.
     
unityunity