How do I draw a tilemap within unity3d?

| | August 5, 2015

I’m pretty new to Unity and after a bit of googling around I have come up with this code to draw my tilemap (the script is attached to my camera).

I am simply trying to use nested for-loops to draw a grid of grass tiles, here is my code:

public class DrawMap : MonoBehaviour {

// Use this for initialization
void Start () {

    Sprite grass = (Sprite)Instantiate(Resources.Load("Grass"));
    float x, y;

    for (int i = 0; i < 20; i++) {  
                    for (int j = 0; j < 20; j++) {
                        x = i * 1.28f;
                        y = j * -1.28f;
                        Instantiate(grass, new Vector3 (x, y, 0f), Quaternion.identity);

                    }
            }
}

// Update is called once per frame
void Update () {

}

I keep getting an error where I initialize “grass” saying the it cannot cast the source type from the destination type. I created “grass” to be a prefab from a slice of a spritesheet that i imported.

Any help would be greatly appreciated

One Response to “How do I draw a tilemap within unity3d?”

  1. Ok seems as no one is replying to you, I will provide you with a basic commented example.

    I assume you have a “Resources” folder inside of your “Assets” folder.
    I also assume you have a “Prefabs” folder inside of your “Resources” folder.

    You will need to create an empty GameObject in your scene. Attach a SpriteRenderer component to that object and then drag your desired grass sprite into the Sprite section of the SpriteRenderer. Drag that object into your “Resources/Prefabs” folder. The destination is important because we will be loading it from script later. Delete the initial (not prefab in folder) GameObject in your scene because we already have a copy of it.

    Now you have created a tile prefab which can be used for the basic example tile map. Please note that this is for explanation purposes and would need some slight modifications to have multiple tiles instead of just one.

    Now you will need to create a new GameObject in your scene and name it “TileMap” or whatever you want…

    Create a new C# script and name that “TileMap” or “Map” or whatever you want… Attach that script to the “TileMap” GameObject.

    Open up the C# script and insert the below code into it.

    NOTE the code is commented and I shouldn’t have to re-explain it to you. Good luck.

    //Place a gameobject with a sprite renderer attached and the grass tile in that. 
    //Create it into a prefab and place it into your "Resources" folder.
    public Transform tilePrefab;
    
    //Tilemap width and height
    public int mapWidth = 5;
    public int mapHeight = 5;
    
    //Size you want your tile in unity units
    public float tileSize = 1.28f;
    
    //2D array to hold all tiles, which makes it easier to reference adjacent tiles etc.
    public Transform[,] map;
    
    void Start () 
    {
        //Load prefab "Grass" from "Resources/Prefabs/" folder.
        tilePrefab = Resources.Load <Transform> ("Prefabs/Grass");
    
        //If we can't find the prefab then log a warning.
        if (!tilePrefab)
            Debug.LogWarning ("Unable to find TilePrefab in your Resources folder.");
    
        //Initialize our 2D Transform array with the width and height
        map = new Transform[mapWidth, mapHeight];
    
        //Iterate over each future tile positions for x and y
        for (int y = 0; y < mapHeight; y++)
        {
            for (int x = 0; x < mapWidth; x++)
            {
                //Instantiate tile prefab at the desired position as a Transform object
                Transform tile = Instantiate (tilePrefab, new Vector3 (x * tileSize, y * tileSize, 0), Quaternion.identity) as Transform;
                //Set the tiles parent to the GameObject this script is attached to
                tile.parent = transform;
                //Set the 2D map array element to the current tile that we just created.
                map[x, y] = tile;
            }
        }
    }
    
    //Returns a tile from the map array at x and y
    public Transform GetTileAt (int x, int y)
    {
        if (x < 0 || y < 0 || x > mapWidth || y > mapHeight)
        {
            Debug.LogWarning ("X or Y coordinate is out of bounds!");
            return null;
        }
        return map[x, y];
    }
    
    void Update () 
    {
    
    }
    

Leave a Reply