|
1 |
| -// Requires: Unity 5.5.0a1 or later |
2 |
| -// Fills tilemap with random tiles |
3 |
| -// Usage: Attach this script to Tilemap layer, assign tiles, hit play |
| 1 | +// tested with unity version: 2017.2.0b4 |
| 2 | +// info: Fills tilemap with random tiles |
| 3 | +// usage: Attach this script to empty gameobject, assign some tiles, then press play |
4 | 4 |
|
5 | 5 | using UnityEngine;
|
| 6 | +using UnityEngine.Tilemaps; |
6 | 7 |
|
7 |
| -public class RandomTiles : MonoBehaviour |
| 8 | +namespace UnityLibary |
8 | 9 | {
|
9 |
| - public Tile[] tiles; |
10 |
| - |
11 |
| - void Start() |
| 10 | + public class RandomTiles : MonoBehaviour |
12 | 11 | {
|
13 |
| - RandomTileMap(); |
14 |
| - } |
| 12 | + public int width = 32; |
| 13 | + public int height = 32; |
15 | 14 |
|
16 |
| - void RandomTileMap() |
17 |
| - { |
18 |
| - TileMap map = GetComponent<TileMap>(); |
| 15 | + public Tile[] tiles; |
19 | 16 |
|
20 |
| - int sizeX = 32; |
21 |
| - int sizeY = 16; |
| 17 | + void Start() |
| 18 | + { |
| 19 | + RandomTileMap(); |
| 20 | + } |
22 | 21 |
|
23 |
| - for (int x = 0; x < sizeX; x++) |
| 22 | + void RandomTileMap() |
24 | 23 | {
|
25 |
| - for (int y = 0; y < sizeY; y++) |
| 24 | + // validation |
| 25 | + if (tiles == null || tiles.Length < 1) |
| 26 | + { |
| 27 | + Debug.LogError("Tiles not assigned", gameObject); |
| 28 | + return; |
| 29 | + } |
| 30 | + |
| 31 | + var parent = transform.parent; |
| 32 | + if (parent == null) |
| 33 | + { |
| 34 | + var go = new GameObject("grid"); |
| 35 | + go.AddComponent<Grid>(); |
| 36 | + transform.SetParent(go.transform); |
| 37 | + } else |
| 38 | + { |
| 39 | + if (parent.GetComponent<Grid>() == null) |
| 40 | + { |
| 41 | + parent.gameObject.AddComponent<Grid>(); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + TilemapRenderer tr = GetComponent<TilemapRenderer>(); |
| 46 | + if (tr == null) |
| 47 | + { |
| 48 | + tr = gameObject.AddComponent<TilemapRenderer>(); |
| 49 | + } |
| 50 | + |
| 51 | + Tilemap map = GetComponent<Tilemap>(); |
| 52 | + if (map == null) |
26 | 53 | {
|
27 |
| - var tilePos = new Vector3Int(x, y, 0); |
28 |
| - map.SetTile(tilePos, tiles[Random.Range(0, tiles.Length)]); |
| 54 | + map = gameObject.AddComponent<Tilemap>(); |
| 55 | + } |
| 56 | + |
| 57 | + |
| 58 | + // random map generation |
| 59 | + Vector3Int tilePos = Vector3Int.zero; |
| 60 | + for (int x = 0; x < width; x++) |
| 61 | + { |
| 62 | + for (int y = 0; y < height; y++) |
| 63 | + { |
| 64 | + tilePos.x = x; |
| 65 | + tilePos.y = y; |
| 66 | + map.SetTile(tilePos, tiles[Random.Range(0, tiles.Length)]); |
| 67 | + } |
29 | 68 | }
|
30 | 69 | }
|
31 | 70 | }
|
32 |
| - |
33 | 71 | }
|
0 commit comments