Hi I want to disable all scripts that are set to gamobject childs, for example with the next script i disable all Mesh Render, that are inside a gameobject, the question is how can i dasable all scripts
foreach (GameObject go in GameObject.FindGameObjectsWithTag (“ParentTag”)) {
Renderer[ ] rs = go.GetComponentsInChildren();
foreach(Renderer r in rs)
r.enabled = false;
}
Renderer isn’t derived from MonoBehaviour, so you’ll have to use an additional method. Try this:
foreach (GameObject go in GameObject.FindGameObjectsWithTag ("ParentTag")) {
foreach (Component component in go.GetComponentsInChildren(typeof(Component))) {
SetComponentEnabled(component, false);
}
}
public void SetComponentEnabled(Component component, bool value) {
if (component == null) return;
if (component is Renderer) {
(component as Renderer).enabled = value;
} else if (component is Collider) {
(component as Collider).enabled = value;
} else if (component is Animation) {
(component as Animation).enabled = value;
} else if (component is Animator) {
(component as Animator).enabled = value;
} else if (component is AudioSource) {
(component as AudioSource).enabled = value;
} else if (component is MonoBehaviour) {
(component as MonoBehaviour).enabled = value;
} else {
Debug.Log("Don't know how to enable " + component.GetType().Name);
}
}
The issue is that each of those component types (Renderer, Collider, etc.) define their own, separate enabled properties, so they need to be handled separately.
I believe he was just using Renderer as an example. If you just want to disable user scripts, which would all be derived from MonoBehaviour, that’s the base class to look for.
That being said, Animation, Animator, AudioSource and MonoBehaviour all derive from Behaviour, so your function could be refactored as follows:
void SetChildComponentsEnabled(bool value) {
var parentObjects = GameObject.FindGameObjectsWithTag ("ParentTag");
foreach (var gameObject in parentObjects) {
var components = gameObject.GetComponentsInChildren<Component>();
foreach(var component in components) {
var collider = component as Collider;
if (collider) collider.enabled = value;
var renderer = component as Renderer;
if (renderer) renderer.enabled = value;
var behaviour = component as Behaviour;
if (behaviour) behaviour.enabled = value;
}
}
}
Thanks! I’m sure I also missed some other non-Behaviour components, too. It’s probably worthwhile for the OP to check what components are on the scene’s GameObjects and check their inheritance hierarchy.