- Home /
Removing only colliders in a game object and its children
This is my first attempt at a custom editor and my Google-fu failed me. I was wondering what's wrong with my code. My objective is to assign a GameObject via the Inspector then click to remove the Collider components from all of its children (rather than the laborious task of clicking each one and deleting the Collider individually). It's a modification from the tutorial Build Object script.
----Editor-----
using UnityEngine;
using System.Collections;
using UnityEditor;
[CustomEditor (typeof(ComponentDestroyerScript))]
public class ComponentDestroyerEditor : Editor {
public override void OnInspectorGUI () {
DrawDefaultInspector();
ComponentDestroyerScript myScript = (ComponentDestroyerScript)target;
if (GUILayout.Button("Destroy Colliders")) myScript.DestroyColliders();
}
}
-------Script-------
using UnityEngine;
using System.Collections;
public class ComponentDestroyerScript : MonoBehaviour {
public Transform myObject;
private var childCollider;
public void DestroyColliders() {
foreach (Transform child in myObject) {
childCollider = child.GetComponentsInChildren<Collider>();
DestroyImmediate(childCollider);
}
}
}
Answer by Soraphis · Apr 23, 2016 at 09:23 PM
GetComponentsInChildren will return a list of components. you have to iterate through it to get the collider components
public void DestroyColliders() {
foreach (Transform child in myObject) {
childCollider = child.GetComponentsInChildren<Collider>();
foreach (collider in childCollider) {
DestroyImmediate(collider);
}
}
}
Hi, thanks. Your code didn't quite work by its own (I needed childCollider to be in an array and collider is supposed to be preceded by Collider), but it gave me some insight into fixing the code properly.
public Transform myObject;
Collider[] childColliders;
public void DestroyColliders() {
childColliders = myObject.GetComponentsInChildren<Collider>();
foreach (Collider collider in childColliders) {
DestroyImmediate(collider);
}
}
Your answer
Follow this Question
Related Questions
Toggle bool reset after using DestroyImmediate (On Editor Script) 0 Answers
I give up. My Foldout creates a very small space when expanded. How do I get rid of it? 0 Answers
How to use OnWIllDeleteAsset - Not being called 2 Answers
(Editor) How to delete duplicate components from GameObject that persists when the scene reloads 0 Answers