- Home /
Prefab, procedural attachment of child, childCount return 0
I have 2 prefabs, A and B. B has it's own sub-child, C.
A is created procedural and B is attached to A from A:s function Start() where B has it's parent set to A.
function otherFunction(){
objA = Instantiate(A, pos, rot);
}
public class A : MonoBehaviour{
void Start(){
objB = Instantiate(B, position, rotation);
objB.parent = A;
}
}
In the game object hierarchy this gives the correct setup wher C is child of B who is child to A.
However, if I try to loop through the children of A or get the .childCount, it returns 0.
function void CountChild(){
numOfChildren = objA.transform.childCount;
}
Also, if I try to reach a child by the A.transform.FindChild("B") function it returns null.
Can anyone give me a pointer to what's going on here and why I can't reach an objects children when it's created during runtime. The exact same procedure works just fine if i have a regular object with the same setup in the scene from start.
Answer by poday · Feb 09, 2013 at 02:43 AM
The first thing I'd look at is: "When are you calling "CountChild()"?". When you Instantiate an object that object's components' Awake methods are called. But their Start methods are called some indeterminate time later. I've created objects that received collision events before their Start method was called. I believe that the docs say "next frame" or something to that extent.
In my experience any initialization code that relates to code outside the class needs to go into the Awake method as there is no guarantee that Start will be called before other code starts interacting with the class instance.
Your answer
Follow this Question
Related Questions
Make a simple tree 1 Answer
Instantiate a Prefab as child 0 Answers
How to Instantiate Prefab as Child of Player OnTriggerEnter 0 Answers
Instantiating prefabs as child of a gameobject 1 Answer
Give prefab a parent 2 Answers