- Home /
Does .SetActive work with components?
Wondering if I can use .SetActive to iterate through a GameObject and it's children to enable/disable that part of all of them.
Otherwise, I'll stick to GetComponentsInChildren.
If not, this would be a damn cool feature.
Isn't that exactly what you do with GetComponentsInChildren ? .SetActive is just setting a bool value, so I don't see how that would be able to iterate over all components of a gameObject.
Because .SetActive, when used like GameObject.SetActive = true, it becomes true for all children. However components are a little different in that way, but the only thing they would have to consider in program$$anonymous$$g it to work with components, is to check if each child has that component. I just think it would be a nice shortcut, if it isnt one already, for child components.
It doesn't exist I'm afraid - and yep it would be handy :) The other thing that would be handy was if Colliders shared the same enabled status as Behaviours - which they do not :(
Answer by whydoidoit · Oct 17, 2013 at 12:19 PM
This might help:
using UnityEngine;
public static class EnableHelper
{
public static void EnableChildren(this Component component, System.Func<Component, bool> predicate, bool enabled = true)
{
foreach(var c in component.GetComponentsInChildren<Collider>(true))
if(predicate(c))
c.enabled = enabled;
foreach(var c in component.GetComponentsInChildren<Rigidbody>(true))
if(predicate(c))
c.isKinematic = !enabled;
foreach(var c in component.GetComponentsInChildren<Behaviour>(true))
if(predicate(c))
c.enabled = enabled;
}
public static void EnableChildren(this Component component, bool enabled = true)
{
component.EnableChildren((a)=>true, enabled);
}
public static void EnableChildren(this GameObject go, bool enabled = true)
{
go.transform.EnableChildren((a)=>true, enabled);
}
public static void EnableChildren(this GameObject go, System.Func<Component, bool> predicate, bool enabled = true)
{
go.transform.EnableChildren(predicate, enabled);
}
}
Then you can just do:
gameObject.EnableChildren();
gameObject.EnableChildren(false);
gameObject.EnableChildren(c=>c.CompareTag("Something"));
It's more like SetActiveRecursively than the new SetActive though.
Your answer
Follow this Question
Related Questions
How to set false components to true? 1 Answer
sync renderer.enabled or SetActive() over network? 2 Answers
If i disable a GameObject does all it's components get disabled also? 2 Answers
Set Objects Child to Active/Inactive(Solved) 5 Answers
Why are some components not inherited from Behaviour when they should? 1 Answer