《敏捷编程系列》
更改后代码:
using UnityEngine; using UnityEditor; using System.Collections; public class MapGenerator: EditorWindow { /// <summary> /// The height of the meta prefab. /// </summary> int prefabHeight = 1; int prefabWidth = 1; const int horizontalNumber = 8; const int verticalNumber = 8; /// <summary> /// The map array. /// </summary> public Object[,] mapArray = new Object[verticalNumber,horizontalNumber]; [MenuItem ("MyTools/MapGenerator")] static void Init () { MapGenerator window = (MapGenerator)EditorWindow.GetWindow(typeof (MapGenerator)); window.Show(); } void OnGUI () { // setting of prefab GUILayout.Label ("Basic Settings", EditorStyles.boldLabel); prefabHeight = EditorGUILayout.IntField ("PrefabHeight:",prefabHeight); prefabWidth = EditorGUILayout.IntField ("PrefabWidth:",prefabWidth); EditorGUILayout.Space(); // the area of map editor GUILayout.Label ("MapEditor", EditorStyles.boldLabel); for(int j = 0;j < horizontalNumber;j++) { EditorGUILayout.BeginHorizontal(); for(int i = 0;i < verticalNumber;i++) mapArray[i,j] = EditorGUILayout.ObjectField(mapArray[i,j],typeof(Object), true); EditorGUILayout.EndHorizontal(); } EditorGUILayout.Space(); // the area of button EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Create")) Create(); if (GUILayout.Button("Reset")) Reset(); EditorGUILayout.EndHorizontal(); } private void Create() { for(int j = 0;j < horizontalNumber;j++) { for(int i = 0;i < verticalNumber;i++) { if(null == mapArray[i,j]) continue; assertNull(GameObject.Find("Tile" + j + i)); Vector3 pVector = new Vector3(i*prefabWidth, (horizontalNumber-j)*prefabHeight, 0); generateObject(pVector,j,i); } } } private void Reset() { prefabWidth = 1; prefabHeight = 1; for(int j = 0;j < horizontalNumber;j++) { for(int i = 0;i < verticalNumber;i++) { if(null == mapArray[i,j]) continue; assertNull(GameObject.Find("Tile" + j + i)); mapArray[i,j] = null; } } } /// <summary> /// Generate object and assign some properties /// </summary> /// <param name='pos'> /// Generate position. /// </param> /// <param name='h'> /// Index of height /// </param> /// <param name='w'> /// Index of weight. /// </param> protected void generateObject(Vector3 pos,int h,int w) { Object obj = Instantiate(mapArray[h,w],pos, Quaternion.identity); obj.name = "Tile" + h + w; (obj as GameObject).transform.localScale = new Vector3(prefabWidth,prefabHeight,1); } /// <summary> /// Asserts the gameObject is null. /// </summary> /// <param name='gameObject'> /// Game object. /// </param> protected void assertNull(GameObject gameObject) { if(gameObject) DestroyImmediate(gameObject); } }