What happens to the code of the Start/Awake function when I deactivate a gameobject?

To populate a dungeon, I instantiate the enemies, initialize them through an interface and then deactivate them until the player enters the room where those enemies are positioned.

If I deactivate an enemy before the Start() function or the interface function, or even the Awake() function of an enemy are done, what happens to the code when I reactivate the enemy?

Does Unity let those functions end their code and only then, it deactivate the scripts? Or does it interrupt them and resume them when the gameObject is activated again? Or does it interrupt them and never resume them since they run only once per life time?


In Unity nothing can be interrupted (with the exception of coroutine but they aren’t methods in the first place) as everything (scripting related) runs in a single thread. So no matter what method is currently running it can’t be “interrupted” by another from “outside”.

If i got you right you have a prefab which you instantiate (with Instantiate) at runtime. The behaviour of Awake and Start depends on the active / enabled state of your prefab. If the script is enabled and the gameobject is active in the prefab, this would happen:

// C#
GameObject inst = (GameObject)Instantiate(prefab);

When call Instantiate and (as said above) the script and gameobject is enabled / active, Awake will be called immediately. Actually Awake will be called inside Instantiate. So when Instantiate returns Awake has already been called and finished.

Start on the other hand will always be called at the beginning of the next frame. So if you immediately disable the gameobject Start won’t be called until you reenable it.

However if the prefab is already disabled, even Awake won’t be called until you enable it. Even here Awake will be called immediately when you enable the instance. Keep in mind that “.enabled” is not a variable but a property. So when assigning “true” to that property you actually call the set method. Awake will be called from inside the set method. So Awake will have finished execution when the set method of the property returns.

Start always behaves the same. It’s always called at the beginning of the next frame.

Also, as you can read in the docs, Awake as well as Start will only be called once in the lifetime of the object. So if both got already called nothing will happen if you disable / enable them again.