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. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Making the old Scene "inactive" - how to handle persistent objects?

Discussion in 'Scripting' started by jerotas, Apr 30, 2018.

  1. jerotas

    jerotas

    Joined:
    Sep 4, 2011
    Posts:
    5,555
    I have a Game Object that marked as "do not delete" so it will stick around when a new Scene is loaded. This seems to be an old Unity concept maybe? With newer Scene Manager code, you can load a new Scene async and then tell the original Scene to become inactive when the new one is loaded. Is there a way to make a persistent object come over to the new Scene instead of just stopping running when it's in the inactive Scene?
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
  3. rakkarage

    rakkarage

    Joined:
    Feb 3, 2014
    Posts:
    683
    https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
     
  4. jerotas

    jerotas

    Joined:
    Sep 4, 2011
    Posts:
    5,555
  5. jerotas

    jerotas

    Joined:
    Sep 4, 2011
    Posts:
    5,555
  6. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    There are built-in events for scene loaded, unloaded, and active scene changed. I think beyond that, you'd have to create your own.

    Just out of curiosity, does your object get destroyed when you load a new scene and unload the old one or just stop running your scripts? I haven't a lot of experience with that, so just wondering. :)
    Maybe I'd check that out some time to see.
     
  7. rakkarage

    rakkarage

    Joined:
    Feb 3, 2014
    Posts:
    683
    that is not normal scripts on objects that use
    DontDestroyOnLoad(this.gameObject);
    should continue to run after the new scene is loaded and the old one removed i made a simple test i can share if u like

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.SceneManagement;
    3. public class Save : MonoBehaviour
    4. {
    5.     private static bool created = false;
    6.     void Awake()
    7.     {
    8.         if (!created)
    9.         {
    10.             DontDestroyOnLoad(this.gameObject);
    11.             created = true;
    12.             Debug.Log("Awake: " + this.gameObject);
    13.         }
    14.     }
    15.     [ContextMenu("LoadScene")]
    16.     public void LoadScene()
    17.     {
    18.         SceneManager.LoadSceneAsync(1, LoadSceneMode.Single);
    19.     }
    20.     public void FixedUpdate()
    21.     {
    22.         Debug.Log("Update");
    23.     }
    24. }