Is there any better way to deactivate child gameobjects from a script attached to the parent gameobject?
this.gameObject.transform.Find("ChildToKill").gameObject.SetActive(false);
Is there any better way to deactivate child gameobjects from a script attached to the parent gameobject?
this.gameObject.transform.Find("ChildToKill").gameObject.SetActive(false);
First drop back everything that is implicit. Save yourself some typing.
transform.Find("ChildToKill").gameObject.setActive(false);
To disable a child object by its name, i think so.
But its is not the common pattern, we usually use a directly reference setted in editor.
This is a simple extension method that does what you want:
public static class GameObjectExtensions
{
/// <summary>
/// Gets the child gameObject whose name is specified by 'wanted'
/// The search is non-recursive by default unless true is passed to 'recursive'
/// </summary>
public static GameObject GetChild(this GameObject inside, string wanted, bool recursive = false)
{
foreach (Transform child in inside.transform)
{
if (child.name == wanted) return child.gameObject;
if (recursive)
{
var within = GetChild(child.gameObject, wanted, true);
if (within) return within;
}
}
return null;
}
}
Usage:
gameObject.GetChild("childname").SetActive(false);