Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

When is script instantiated? (re Awake())

Discussion in 'Scripting' started by IngeJones, May 27, 2017.

  1. IngeJones

    IngeJones

    Joined:
    Dec 11, 2013
    Posts:
    129
    I am aware that the documentation states that Awake() and Start() only run once per script instance. But what I am not familiar with is: Is it a new instance when you reload a game after saving and quitting? What about when you have left the scene with an object in it (with your script attached) and go back to that scene? Does that count as a new instance so that Awake() runs again? And what about when you have deactivated and reactivated? I feel as if Awake() should naturally run then, too. What are the facts about these situations?
     
  2. JoshuaMcKenzie

    JoshuaMcKenzie

    Joined:
    Jun 20, 2015
    Posts:
    916
    when you instantiate a Monobehaviour (via instantiating a prefab, adding a component at runtime, or loading a scene with one in its hierarchy) Awake will fire immediately. then on the first frame that its enabled, after the frame Awake was called, Start will be called. This delay is purposely set so that if multiple objects are instantiated in parallel (like on level load) Awake allows each one to set up local data while Start allows the multiple objects to connect to each other without worrying about race conditions. As such use Awake to prepare data that can only be accessed through the script, while in Start set up data that refers to other Scripts or Gameobjects.

    When you open the game again the script is a completely new instance so it will call Awake and Start at those times. if you unload the level the instance is destroyed so a new instance will be created if you go back and load that scene again. they are separate instances so Awake and Start will run on each of them.

    Disabling a script does not destroy the script so Awake / Start will not be called again when you re-enable it. its still the same instance and Awake/Start will only be called by Unity once per a script's existence.
     
    modern12pl and IngeJones like this.
  3. IngeJones

    IngeJones

    Joined:
    Dec 11, 2013
    Posts:
    129
    Thank you! I think that fairly comprehensively answers my question :)
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    OnEnable (/OnDisable) will run when Activated/deactivated, too - to fill in a part of what you brought up.