- Home /
A GameObject That's Not Active In The Hierarchy Still Calling Its Start Method?
Hi folks. Have a curious thing happening, which as far as I can see is either a Unity bug, or illustrates that I have a serious misunderstanding of how Unity works.
Essentially, I have two GameObjects, each with a script attached, ParentCreator and ChildToBeDeactivated. ParentCreator, in it's awake call, is supposed to create a new GameObject, deactivate it, and parent the child object to the new deactivated GameObject. Like so:
public class ParentCreator : MonoBehaviour {
ChildToBeDeactivated objectToParent;
void Awake(){
parenter = new GameObject();
objectToParent.gameObject.transform.parent = parenter;
parenter.gameObject.SetActive(false);
}
}
public class ChildToBeDeactivated : MonoBehaviour {
void Start(){
Debug.Log("hello. this shouldn't happen.");
}
}
I'd expect ChildToBeDeactivated's Debug.Log never to happen; ParentCreator's Awake should happen before the Child's Start, and so the Child should be deactivated in the hiearchy by the time it's start would happen. However, this is not what's happening, I'm seeing the Child's Start method happening!
Why is this?
Answer by sacredgeometry · Aug 16, 2019 at 09:52 AM
*MonoBehaviour.Start()
Start is called on the frame when a script is enabled just before any of the Update methods are called the first time. Like the Awake function, Start is called exactly once in the lifetime of the script. However, Awake is called when the script object is initialised, regardless of whether or not the script is enabled. Start may not be called on the same frame as Awake if the script is not enabled at initialisation time.*
It's as per the documentation:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html
what you want instead perhaps your own bool or enum and/ or event to determine the state of your MonoBehaviour as I cant see a way to instantiate the object in a deactivated state.
There is nothing in your code that guarentees that the ParentCreator 's Awake method, does the SetActive call before the ChildToBeDeactivated 's Start event. Which gets invoked as part of the objects construction.
If it's synchronous it outright wont work if it's asynchronous it's a possible race condition.
Right, Start is essentially a scheduled event that is scheduled when the object is created. If the object is enabled / active when the object is created, the Start method is scheduled and will execute.