1
\$\begingroup\$

I loaded my tileset asset TileSheet.png using the Tile Palette (Window -> 2D -> Tile Palette).

This created the folder "grass_tiles" with multiple asset files, one named "TileSheet_168.asset".

My goal is to write a script that randomly generates grass tiles within my 128 x 128 tile map.

I envision the code looking something like this:

tilemap.SetTile(new Vector3Int(x, y, 0), "TileSheet_" + TileNum + ".asset);

...where TileNum is a randomly generated integer between 1 and 750 (assuming that's what SetTile even does).

Current code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine; 
using UnityEngine.Tilemaps;

public class drawMap : MonoBehaviour {
    public Tile grassTile;
    public Tilemap ChessMap;

    // Start is called before the first frame update
    void Start()
    {
        RenderMap(GenerateArray(128, 128), ChessMap, grassTile);
    }

    public static int[,] GenerateArray(int width, int height)
    {
        int colorControl = 0;
        int cellFig = 0;
        int[,] map = new int[width, height];

        for (int x = 1; x <= map.GetUpperBound(0); x++)
        {
            cellFig = x / 16;

            if (Mathf.Floor(cellFig) == cellFig) {
                if (colorControl == 0) { colorControl = 1; } else { colorControl = 0; }
            }
            for (int y = 1; y <= map.GetUpperBound(1); y++)
            {
                if (colorControl == 0)
                {
                    map[x, y] = 0;
                }
                else
                {
                    map[x, y] = 1;
                }
                Debug.Log("Map Coordinates x: " + x);
                Debug.Log("Map Coordinates y: " + y);
                Debug.Log("color: " + colorControl);
            }
            if (colorControl == 0) { colorControl = 1; } else { colorControl = 0; }
        }
        return map;
    }

    public static void RenderMap(int[,] map, Tilemap tilemap, TileBase tile)
    {
        //Clear the map (ensures we dont overlap)
        tilemap.ClearAllTiles();
        //Loop through the width of the map
        for (int x = 0; x < map.GetUpperBound(0); x++)
        {
            //Loop through the height of the map
            for (int y = 0; y < map.GetUpperBound(1); y++)
            {
                // 1 = tile, 0 = no tile
                if (map[x, y] == 1)
                {
                    tilemap.SetTile(new Vector3Int(x, y, 0), "TileSheet_" + TileNum + ".asset);
                }
            }
        }
    } 
}

Where I need help is the loading of the asset, referencing the asset, and setting of the asset.

I only need this script once, because after it's done, hopefully the GameObject can remember (as if I used the Tile Palette tool).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.