Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class Grid : MonoBehaviour {
- public float time1 = 35f;
- public float time2 = 50f;
- public Vector2 gridSize = new Vector2(10, 10);
- public Vector2 distance = new Vector2(1f, 1f);
- public OnClick prefab;
- public Material mat;
- [HideInInspector]
- public OnClick randomGO;
- private float counter;
- private OnClick[,] instances;
- public void Start() {
- if(instances != null)
- foreach(var i in instances)
- Destroy(i.gameObject);
- instances = new OnClick[(int)gridSize.x, (int)gridSize.y];
- counter = 0f;
- }
- private void Update() {
- if(Time.time > counter) {
- var x = Random.Range(0, (int)gridSize.x);
- var y = Random.Range(0, (int)gridSize.y);
- while(instances[x, y])
- if(++x == (int)gridSize.x) {
- x = 0;
- if(++y == (int)gridSize.y)
- y = 0;
- }
- instances[x, y] = Instantiate(prefab, transform.position, transform.rotation) as OnClick;
- instances[x, y].transform.parent = transform;
- instances[x, y].transform.localPosition += new Vector3(x * distance.x, 0f, y * distance.y);
- instances[x, y].name = string.Format("{0}-{1}", x, y);
- instances[x, y].grid = this;
- var hasSpace = false;
- for(x = 0; x < (int)gridSize.x; x++)
- for(y = 0; y < (int)gridSize.y; y++)
- if(!instances[x, y]) {
- hasSpace = true;
- break;
- }
- float time = Random.Range(time1, time2);
- counter = hasSpace ? (Time.time + 1f / time) : float.PositiveInfinity;
- if(!hasSpace) {
- x = Random.Range(0, (int)gridSize.x);
- y = Random.Range(0, (int)gridSize.y);
- randomGO = instances[x, y];
- randomGO.GetComponentInChildren<Renderer>().material = mat;
- Debug.LogFormat("Random GO is {0}", randomGO);
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment