Search Unity

Spawning Sprites on Certain Tiles

Discussion in '2D' started by unity_4amo1092TwtO7Q, Sep 7, 2021.

  1. unity_4amo1092TwtO7Q

    unity_4amo1092TwtO7Q

    Joined:
    Sep 7, 2021
    Posts:
    1
    I am working on a top-down 2D lawnmowing game, and I want to spawn blades of grass on the level. I am using tilemaps to design levels and I am hoping to be able to place a green tile, and have grass blade sprites spawn randomly across those tiles when the level starts, but not across tiles that are sidewalks or roads. I have worked out how to spawn the sprites, but I have gotten stuck on trying to get information from the tilemap. Can anyone recommend a way to detect certain tiles in a tilemap (or any active tile in a grass specific tilemap), and have that communicate with a grass spawning script?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,689
    I think what you're looking for is this:

    https://docs.unity3d.com/Manual/Tilemap-ScriptableTiles.html

    Caveat: I've not tinkered much with them but it seems they could (with perhaps additional scripting) do exactly what you want as far as special behavior in special parts of your map.
     
  3. Lo-renzo

    Lo-renzo

    Joined:
    Apr 8, 2018
    Posts:
    1,511
    Approach 1: Using Scripting API to write additional tiles for the grass blades on top of grass tiles.

    https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.html

    Code (CSharp):
    1. public class GrassSpawner : MonoBehaviour
    2. {
    3.     // connect these properties up in the Inspector
    4.     public Tilemap grassTilemap;  // green tiles
    5.     public Tilemap grassTuftTilemap;  // grass blades, needs to have order so that render on top of grassTilemap
    6.     public TileBase grassTile;
    7.     public TileBase grassTuft;
    8.  
    9.    void Start()
    10.    {
    11.        SpawnGrassTufts();
    12.    }
    13.  
    14.     void SpawnGrassTufts()
    15.     {
    16.             foreach (var cell in grassTilemap.cellBounds.allPositionsWithin)
    17.             {
    18.                 if (tilemap.GetTile(cell) == grassTile && Random.value < .33f)
    19.                 {
    20.                     // 1/3 of grass tiles will receive grass tuft on top
    21.                     grassTuftTilemap.SetTile(cell, grassTuft);
    22.                 }
    23.             }
    24.     }
    25. }

    Approach 2: use RandomTile


    Another way to do this would be to create a RandomTile. See 2D Tilemap Extras package, available in the Package Manager. You would have the sprite sometimes be plain green. Other times, you'd use a different sprite: green plus blades.

    https://forum.unity.com/threads/tilemap-extras-preview-package-is-now-available.962664/
     
    Last edited: Sep 8, 2021