Skip to content

Commit e21a584

Browse files
authored
Update RandomTiles.cs #15
1 parent 85295fe commit e21a584

File tree

1 file changed

+57
-19
lines changed

1 file changed

+57
-19
lines changed

Scripts/2D/Tilemaps/RandomTiles.cs

Lines changed: 57 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,71 @@
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
44

55
using UnityEngine;
6+
using UnityEngine.Tilemaps;
67

7-
public class RandomTiles : MonoBehaviour
8+
namespace UnityLibary
89
{
9-
public Tile[] tiles;
10-
11-
void Start()
10+
public class RandomTiles : MonoBehaviour
1211
{
13-
RandomTileMap();
14-
}
12+
public int width = 32;
13+
public int height = 32;
1514

16-
void RandomTileMap()
17-
{
18-
TileMap map = GetComponent<TileMap>();
15+
public Tile[] tiles;
1916

20-
int sizeX = 32;
21-
int sizeY = 16;
17+
void Start()
18+
{
19+
RandomTileMap();
20+
}
2221

23-
for (int x = 0; x < sizeX; x++)
22+
void RandomTileMap()
2423
{
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)
2653
{
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+
}
2968
}
3069
}
3170
}
32-
3371
}

0 commit comments

Comments
 (0)