Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

[Resolved] DontDestroyOnLoad question

Discussion in 'Scripting' started by ajsnarr98, Jan 17, 2016.

  1. ajsnarr98

    ajsnarr98

    Joined:
    Jun 15, 2015
    Posts:
    73
    Say I have a script attached to game object, and in "void Awake()" I do "DontDestroyOnLoad(GetComponent<Transform>().gameObject);". When a new scene is loaded after that, are any functions like the Start() function ever called again in that script? Or are one-time functions like the Start() function only ever called once when an object and its components are first loaded?

    If you know of a function that is called when a new scene is loaded, but not only when an object itself is loaded for the first time, please let me know, thanks :)
     
  2. SteveJ

    SteveJ

    Joined:
    Mar 26, 2010
    Posts:
    3,066
    Awake() and Start() are called in the first scene where that object exists. Not in subsequent scenes where the object is already loaded (and preserved due to DontDestroyOnLoad).

    Also, why do this:
    Code (csharp):
    1.  
    2. DontDestroyOnLoad(GetComponent<Transform>().gameObject);
    3.  
    when you can do this:
    Code (csharp):
    1.  
    2. DontDestroyOnLoad(gameObject);
    3.  
     
  3. orb

    orb

    Joined:
    Nov 24, 2010
    Posts:
    3,033
  4. ajsnarr98

    ajsnarr98

    Joined:
    Jun 15, 2015
    Posts:
    73
    I thought "gameObject" was deprecated in newer versions.

    Isn't there any other function other than Awake() and Start() that I can use for what I am looking for though?
     
    Last edited: Jan 17, 2016
  5. ajsnarr98

    ajsnarr98

    Joined:
    Jun 15, 2015
    Posts:
    73
  6. SteveJ

    SteveJ

    Joined:
    Mar 26, 2010
    Posts:
    3,066
    Did you change your post? Feels like you're asking a different question now? :)
     
  7. ajsnarr98

    ajsnarr98

    Joined:
    Jun 15, 2015
    Posts:
    73
    Same question.

    I did change the way I worded one sentence in the second paragraph of the first post immediately after I posted, but unless you loaded the page for the post less than 20 seconds after it was posted you wouldn't have noticed it.