Muk99

Grid

Feb 24th, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.14 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. public class Grid : MonoBehaviour {
  4.  
  5.     public float time1 = 35f;
  6.     public float time2 = 50f;
  7.     public Vector2 gridSize = new Vector2(10, 10);
  8.     public Vector2 distance = new Vector2(1f, 1f);
  9.     public OnClick prefab;
  10.     public Material mat;
  11.     [HideInInspector]
  12.     public OnClick randomGO;
  13.  
  14.     private float counter;
  15.     private OnClick[,] instances;
  16.  
  17.     public void Start() {
  18.         if(instances != null)
  19.             foreach(var i in instances)
  20.                 Destroy(i.gameObject);
  21.  
  22.         instances = new OnClick[(int)gridSize.x, (int)gridSize.y];
  23.         counter = 0f;
  24.     }
  25.  
  26.     private void Update() {
  27.         if(Time.time > counter) {
  28.             var x = Random.Range(0, (int)gridSize.x);
  29.             var y = Random.Range(0, (int)gridSize.y);
  30.  
  31.             while(instances[x, y])
  32.                 if(++x == (int)gridSize.x) {
  33.                     x = 0;
  34.                     if(++y == (int)gridSize.y)
  35.                         y = 0;
  36.                 }
  37.  
  38.             instances[x, y] = Instantiate(prefab, transform.position, transform.rotation) as OnClick;
  39.             instances[x, y].transform.parent = transform;
  40.             instances[x, y].transform.localPosition += new Vector3(x * distance.x, 0f, y * distance.y);
  41.             instances[x, y].name = string.Format("{0}-{1}", x, y);
  42.             instances[x, y].grid = this;
  43.  
  44.             var hasSpace = false;
  45.  
  46.             for(x = 0; x < (int)gridSize.x; x++)
  47.                 for(y = 0; y < (int)gridSize.y; y++)
  48.                     if(!instances[x, y]) {
  49.                         hasSpace = true;
  50.                         break;
  51.                     }
  52.  
  53.             float time = Random.Range(time1, time2);
  54.             counter = hasSpace ? (Time.time + 1f / time) : float.PositiveInfinity;
  55.  
  56.             if(!hasSpace) {
  57.                 x = Random.Range(0, (int)gridSize.x);
  58.                 y = Random.Range(0, (int)gridSize.y);
  59.  
  60.                 randomGO = instances[x, y];
  61.                 randomGO.GetComponentInChildren<Renderer>().material = mat;
  62.  
  63.                 Debug.LogFormat("Random GO is {0}", randomGO);
  64.             }
  65.         }
  66.     }
  67. }
Add Comment
Please, Sign In to add comment