- Home /
Most effective way to get deactivated children?
Hello.
I have a player object with all its potential armor pieces on it and deactivated. I also plan to add its potential weapons. Thing is, I didn't find much on this topic that was updated and that worked on multiple children. There are too many children to hardcode bools for everything. Is there a more effective way to deactivate them all and only activate the one(s) needed?
if you want to specify which child gets activated/desactivated one by one you will need to set it up manually there is no other solution, but if you dont post your code we cant help you
Answer by RaptorRush · Aug 09, 2020 at 08:39 PM
The transform component holds references to all his children, so you can search them by: Index: (Transform.GetChild())
Transform child = yourTransform.GetChild(i);
Name: (Transform.Find())
Transform child = yourTransform.Find("ObjectName");
You can access to the transform of an object:
Transform yourTransform = yourGameObject.transform;
You can get the children count in an object:
int childCount = yourTransform.childCount;
With this you can loop trough all the children of an object:
for (int currentChildI = 0; currentChildI < transform.childCount; currentChildI++) {
Transform currentChild = transform.GetChild(currentChildI);
}
You can also write your own extensions methods to make your life easier, for example:
using UnityEngine;
public class Example : MonoBehaviour {
public Transform swords, hats;//Your containers
private void UsageExamples() {
swords.SetStateOfAllChildren(false);//Would disable all swords
hats.SetStateOfAllChildren(true);//Would enable all hats
//
swords.SetStateOfChild(true, "FireSword");///Would enable the object named "FireSword"
hats.SetStateOfChild(false, 3);///Would disable the object in the index 3 (Zero-based numbering)
}
}
public static class Extensions {
public static void SetStateOfAllChildren(this Transform transform, bool newState) { for (int currentChildIndex = 0; currentChildIndex < transform.childCount; currentChildIndex++) transform.GetChild(currentChildIndex).SetStateOfGameObject(newState); }
public static void SetStateOfChild(this Transform transform, bool newState, string childName) => transform.Find(childName).SetStateOfGameObject(newState);
public static void SetStateOfChild(this Transform transform, bool newState, int childIndex) => transform.GetChild(childIndex).SetStateOfGameObject(newState);
private static void SetStateOfGameObject(this Transform transform, bool newState) => transform.gameObject.SetActive(newState);
}