- Home /
Sporadic Failure of GetComponentInChildren
After about 2 months of learning Unity programming in 2D, I’ve finally hit a problem that I can’t solve by looking through the forums and finding a similar problem.
I have built simple target game that Instantiates prefabs to which I’ve attached sprites, colliders and scripts.
In the Start method of my game logic, I’m grabbing a reference to the target GameObject and, specifically, the script attached to one of its children.
TargetCode target_script = GameObject.Find(game_object_target).GetComponentInChildren<TargetCode> ();
My problem is that about 19 times out of 20, this works fine. The game plays without a problem.
However, occasionally, the above line doesn’t find the script and returns null.
I can hack a solution by adding a later check for the target script when needed in the Update method but I want to know why this problem is happening in the first place.
The only unusual thing I've done is to pass the name of the GameObject through a string but a Debug.Log check shows that this is defined correctly and this doesn’t explain the sporadic nature of the bug. I’ve also added a Debug.Break() to the code and I can see that the target exists and the script should be findable (as it is findable later in the Update).
Are they are known problems with GetComponentInChildren? I wondered about the order of execution of Start methods across Instantiated prefabs but I’ve not come across any similar problems or solutions to this problem.
Many thanks in advance.
Is it possible that your GameObject is not finished created? have you tried doing it on two separate lines of codes? GameObject myObject = GameObject.Find(game_object_target); TargetCode targetScript = myObject.GetComponentInChildren ();
A few questions that will surface the problem.
Are you adding the component (TargetCode) dynamically? If so, are you adding it in Start?
Is the object you are searching already on the scene or does it get created during runtime? If so, does it get created in Start?
Something you have to always remember is that Awake is used to initialize your own component so that it can be ready for use. And start is used to communicate/initialize between components or GameObjects.
Your answer
Follow this Question
Related Questions
Instantiated objects always at position 0,0,0 0 Answers
A node in a childnode? 1 Answer
Is it possible to edit the sub-sub-GameObjects of a prefab in the assets window? 1 Answer
How to add a prefab back to a gameobject that is missing one? 5 Answers
How does Unity retain UnityEngine.Object references? 2 Answers