Skip to content

Commit

Permalink
Update RandomTiles.cs #15
Browse files Browse the repository at this point in the history
  • Loading branch information
unitycoder authored Jul 20, 2017
1 parent 85295fe commit e21a584
Showing 1 changed file with 57 additions and 19 deletions.
76 changes: 57 additions & 19 deletions Scripts/2D/Tilemaps/RandomTiles.cs
Original file line number Diff line number Diff line change
@@ -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<TileMap>();
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<Grid>();
transform.SetParent(go.transform);
} else
{
if (parent.GetComponent<Grid>() == null)
{
parent.gameObject.AddComponent<Grid>();
}
}

TilemapRenderer tr = GetComponent<TilemapRenderer>();
if (tr == null)
{
tr = gameObject.AddComponent<TilemapRenderer>();
}

Tilemap map = GetComponent<Tilemap>();
if (map == null)
{
var tilePos = new Vector3Int(x, y, 0);
map.SetTile(tilePos, tiles[Random.Range(0, tiles.Length)]);
map = gameObject.AddComponent<Tilemap>();
}


// 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)]);
}
}
}
}

}

0 comments on commit e21a584

Please sign in to comment.