From e21a5842a30b39ef44c8846120e50dbef4aed48b Mon Sep 17 00:00:00 2001 From: mika Date: Thu, 20 Jul 2017 23:33:00 +0300 Subject: [PATCH] Update RandomTiles.cs #15 --- Scripts/2D/Tilemaps/RandomTiles.cs | 76 ++++++++++++++++++++++-------- 1 file changed, 57 insertions(+), 19 deletions(-) diff --git a/Scripts/2D/Tilemaps/RandomTiles.cs b/Scripts/2D/Tilemaps/RandomTiles.cs index 1885928..92644c1 100644 --- a/Scripts/2D/Tilemaps/RandomTiles.cs +++ b/Scripts/2D/Tilemaps/RandomTiles.cs @@ -1,33 +1,71 @@ -// Requires: Unity 5.5.0a1 or later -// Fills tilemap with random tiles -// Usage: Attach this script to Tilemap layer, assign tiles, hit play +// tested with unity version: 2017.2.0b4 +// info: Fills tilemap with random tiles +// usage: Attach this script to empty gameobject, assign some tiles, then press play using UnityEngine; +using UnityEngine.Tilemaps; -public class RandomTiles : MonoBehaviour +namespace UnityLibary { - public Tile[] tiles; - - void Start() + public class RandomTiles : MonoBehaviour { - RandomTileMap(); - } + public int width = 32; + public int height = 32; - void RandomTileMap() - { - TileMap map = GetComponent(); + public Tile[] tiles; - int sizeX = 32; - int sizeY = 16; + void Start() + { + RandomTileMap(); + } - for (int x = 0; x < sizeX; x++) + void RandomTileMap() { - for (int y = 0; y < sizeY; y++) + // validation + if (tiles == null || tiles.Length < 1) + { + Debug.LogError("Tiles not assigned", gameObject); + return; + } + + var parent = transform.parent; + if (parent == null) + { + var go = new GameObject("grid"); + go.AddComponent(); + transform.SetParent(go.transform); + } else + { + if (parent.GetComponent() == null) + { + parent.gameObject.AddComponent(); + } + } + + TilemapRenderer tr = GetComponent(); + if (tr == null) + { + tr = gameObject.AddComponent(); + } + + Tilemap map = GetComponent(); + if (map == null) { - var tilePos = new Vector3Int(x, y, 0); - map.SetTile(tilePos, tiles[Random.Range(0, tiles.Length)]); + map = gameObject.AddComponent(); + } + + + // random map generation + Vector3Int tilePos = Vector3Int.zero; + for (int x = 0; x < width; x++) + { + for (int y = 0; y < height; y++) + { + tilePos.x = x; + tilePos.y = y; + map.SetTile(tilePos, tiles[Random.Range(0, tiles.Length)]); + } } } } - }