- Home /
using ExecuteInEditMode to create platforms in the editor
Im trying to create platforms in the editor using the ExecuteInEditMode, witch is a dangerous tool. http://gyazo.com/0eddbff097fe958d112b5360bd200cd0 i haven't finish punting all the bells and whistles in this but the idea is that you select a platform in the array and type in the length of the platform(between 1 and 10 or something) and you get a 1-10 tiles long platform in the editor scene view.
but when i decrease the number of tiles it the editor i get stuck in a infinit loop(I think) and my computer or unity crashes.
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class mapBuilder : MonoBehaviour {
public GameObject[] groundType;
[Range (1,10)]
public int lenght = 3;
void Update() {
while(gameObject.transform.childCount != lenght){
GameObject instaceOfGround =
(GameObject)Instantiate( groundType[0],
transform.position,
Quaternion.identity );
instaceOfGround.transform.SetParent(gameObject.transform);
}
if(gameObject.transform.childCount < lenght){
Transform[] childs;
childs = GetComponentsInChildren<Transform>();
foreach(Transform child in childs ){
if(child != this.transform)
Destroy(child.gameObject);
}
}
}
}
Answer by Landern · Jun 05, 2015 at 02:26 PM
While loops can be very danguous in particular int he Update method since it's already called every frame. However your problem is that the lenght(should be length) being less then the childCount means the break in the while look will never happen. So make sure you check for that and bail early for your destroy if block.
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class mapBuilder : MonoBehaviour {
public GameObject[] groundType;
[Range (1,10)]
public int lenght = 3;
void Update() {
// Add an extra condition on your while loop.
while(gameObject.transform.childCount != lenght && gameObject.transform.childCount < lenght){
GameObject instaceOfGround =
(GameObject)Instantiate( groundType[0],
transform.position,
Quaternion.identity );
instaceOfGround.transform.SetParent(gameObject.transform);
}
if(gameObject.transform.childCount < lenght){
Transform[] childs;
childs = GetComponentsInChildren<Transform>();
foreach(Transform child in childs ){
if(child != this.transform)
Destroy(child.gameObject);
}
}
}
}
I fixed this morning, by simply putting the if loop before the while loop.