How to count child dynamically?
I know that using transform.childCount will print the number of child in a parent. but it only prints one. How to will I know the number of children when it is dynamically changing at a runtime?
here's my code
public class StructureChecker : MonoBehaviour {
void Start(){
update();
}
public void update(){
foreach (Transform t in transform.parent) {
Debug.Log (t.transform.childCount);
}
if (transform.childCount == 0) {
Debug.Log ("Structure is full");
} else {
Debug.Log ("Still has child");
}
}
Answer by ArturoSR · Sep 11, 2016 at 08:47 PM
@joyceeene Hello there.
OK, this is what happens:
foreach (Transform t in transform.parent) {
Debug.Log (t.transform.childCount);
// What already do it's count himself as child,
// it's like: child > parent : childCount('from parent return 1').
}
But if you do this:
GameObject[] childs = new Gameobject[transform.childCount]; // Example 5 childs.
for (int i = 0; i < childs.Length; i++) {
childs[i] = transfom.GetChild(i).gameObject; // Get the game object from the selected child.
// You can use 'Transform' instead 'GameObject', if you want access transform directly.
}
Even, if you want to check just the childs quantity, it's like this:
int childs = transform.chilCount; // This returns total children from parent.
So, as you can see, there is only one thing you need to get the children quantity, and no matter if it is in editor mode or game mode, you can use that to get dynamically the number of children, cheers.
Your answer
Follow this Question
Related Questions
How to ungroup objects to its parent? 1 Answer
Parent is not active...but there is no parent! 0 Answers
My checker work 2 times 0 Answers
Multiple Canvases visual overlap issue 2 Answers
How to detect input in InputField in unity when used in android? 0 Answers