[Unity C#] Create Grids in Unity Editor

[Unity C#] Create Grids in Unity Editor
//Created by Tim & Hang
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteInEditMode]
public class CS_GridSetup : MonoBehaviour {

    [SerializeField] bool createGrids = false;

    [SerializeField] GameObject myGridPrefab;

    [SerializeField] int myColumns = 16;
    [SerializeField] int myRows = 9;

    [SerializeField] Vector2 myBottomLeft = new Vector2 (-8, -4);
    [SerializeField] Vector2 myTopRight = new Vector2 (8, 4);
    [SerializeField] float myPositionZ = 10;

    private List<GameObject> myGrids = new List<GameObject> ();


    // Update is called when something changes in the scene
    void Update () {
        if (createGrids == true) {
            createGrids = false;

            //Clear the existing grids

            foreach (GameObject t_grid in myGrids) {
                GameObject.DestroyImmediate (t_grid);
            }
            myGrids.Clear ();

            //create grids

            for (int i = 0; i < myRows; i++) {
                for (int j = 0; j < myColumns; j++) {
                    Vector3 t_position = new Vector3 (
                                             (myTopRight.x - myBottomLeft.x) / (myColumns - 1) * j + myBottomLeft.x, 
                                             (myTopRight.y - myBottomLeft.y) / (myRows - 1) * i + myBottomLeft.y,
                                             myPositionZ); //Calculate the position
                    GameObject t_grid = Instantiate (myGridPrefab, t_position, Quaternion.identity); //Create the grid
                    myGrids.Add (t_grid); //Add it to the list
                    t_grid.transform.SetParent (this.transform); //Set the parent to this gameObject
                    t_grid.name = myGridPrefab.name + "(" + i + ")(" + j + ")"; //Name it
                }
            }
        }
    }
}


Advertisements