Skip to content

Instantly share code, notes, and snippets.

@Domiii
Created January 31, 2018 08:31
Show Gist options
  • Save Domiii/c23378acb342f485a906d087bbd188bb to your computer and use it in GitHub Desktop.
Save Domiii/c23378acb342f485a906d087bbd188bb to your computer and use it in GitHub Desktop.
/**
* Spawns a wall along the X and Y axes of the WallSpawner, using cubes of given size and materials
*/
using UnityEngine;
using System.Collections;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class WallSpawner2 : MonoBehaviour
{
public int Nx = 10;
public int Ny = 10;
public Material[] Materials = new Material[0];
public GameObject prefab;
private float Gap = 0.1f;
// Use this for initialization
void Start ()
{
CreateBricks ();
}
void Update ()
{
// things to try out: rotate the entire wall slowly
// transform.RotateAround(Vector3.up, 0.01f);
}
public void CreateBricks ()
{
Clear ();
for (var j = 0; j < Ny; ++j) {
var xOffset = (j % 2) == 0 ? .5f : 0;
for (var i = 0; i < Nx; ++i) {
var cube = Instantiate (prefab);
cube.transform.SetParent (transform, false);
var cubeSize = cube.GetComponent<Collider> ().bounds.extents;
var x = i * (2 * cubeSize.x + Gap) + Gap + 2 * cubeSize.x * (1 + xOffset);
var y = j * (2 * cubeSize.y + Gap) + Gap;
cube.transform.localPosition = new Vector3 (x, y, 0);
cube.AddComponent<Rigidbody> ();
cube.AddComponent<BoxCollider> ();
if (Materials.Length > 0) {
var m = j % Materials.Length;
cube.GetComponent<MeshRenderer> ().material = Materials [m];
m = (m + 1) % Materials.Length;
}
}
}
}
public void Clear ()
{
for (var i = transform.childCount - 1; i >= 0; --i) {
DestroyImmediate (transform.GetChild (i).gameObject);
}
}
}
#if UNITY_EDITOR
[CustomEditor (typeof(WallSpawner))]
public class WallSpawnerEditor : Editor
{
public override void OnInspectorGUI ()
{
base.OnInspectorGUI ();
var t = (WallSpawner)target;
if (GUILayout.Button ("Build")) {
t.CreateBricks ();
}
if (GUILayout.Button ("Clear")) {
t.Clear ();
}
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment