- Home /
Editor Script to replace objects (problem with selection)
This is what I have sofar, and it works, but on a game object with 23 children, only 11 of them get changed.
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
public class CreateHolders : MonoBehaviour {
[MenuItem ("Pluto/Place Holders")]
static void PlaceHolders () {
foreach(GameObject go in Selection.gameObjects){
foreach (Transform child in go.transform) {
if(child.tag == "Wall"){
GameObject tempGo = new GameObject(child.name.Replace("TS001_", "WALL"));
tempGo.tag = "WallHolder";
tempGo.transform.parent = Selection.activeTransform;
DestroyImmediate(child.gameObject);
}
}
}
}
}
EDIT1: It appears to only do half of the children First one does 11/23, leaving 12. Second one does 6/12 leaving 6. Third time does 3/6 leaving 3. etc .. strange?
EDIT2: I tried unparenting the items I wanted to destroy and not destroying them, and it still only processed 1/2 of the children. Problem doesn't appear to be with DestroyImmediate().
It is recommended to use Destroy ins$$anonymous$$d of DestroyImmediate. It should also solve your problem.
Edit : Sorry, I forgot that you were in edit mode :/
yea i tried that. doesn't seem to work:
Destroy may not be called from edit mode! Use DestroyImmediate ins$$anonymous$$d. Also think twice if you really want to destroy something in edit mode. Since this will destroy objects permanently. UnityEngine.Object:Destroy(Object) CreateHolders:PlaceHolders() (at Assets/Editor/CreateHolders.cs:19)
Also, see EDIT2
Answer by supercouge · Jul 06, 2013 at 08:20 AM
I tried that and it seems to work.
foreach(GameObject go in Selection.gameObjects){
for(int i = 0; i < go.transform.GetChildCount(); i++) {
DestroyImmediate(go.transform.GetChild(i).gameObject);
i--;
}
}
I'm such a slow typist... Well, as to why this works, it is because you were destroying what you were iterating through, so you skipped every other index. This usually gives a runtime error when done with foreach... Ins$$anonymous$$d of decreasing one from i you could also for (int i = 0; i< go.transform.childCount; )
or while(go.transform.childCount>0)
Your answer
Follow this Question
Related Questions
Auto-Selecting something else in Scene-View? 0 Answers
How can I set a selection-sphere in the editor 1 Answer
Preventing editor deselect on MacOS 1 Answer
Editor selection order 2 Answers