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

DontDestroyOnLoad()

Discussion in 'Scripting' started by aidanseeberg, Jul 19, 2015.

  1. aidanseeberg

    aidanseeberg

    Joined:
    Jul 10, 2015
    Posts:
    26
    Right now, I have a DontDestroyOnLoad function on two of my game objects. I have three scenes, and I only want the two game object stay for one transition, but when the game gets to the final scene, I want the game objects deleted. How do I exactly pick which scenes I want this to happen to.
     
  2. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    One way would be by checking the name of the level :
    Code (CSharp):
    1. if(Application.loadedLevelName == "FinalScene"){
    2. //delete your gameObjects.
    3. }
     
    Kiwasi likes this.
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
  4. GhulamJewel

    GhulamJewel

    Joined:
    May 23, 2014
    Posts:
    351
    You can tagged the two other objects you want destroyed in the later scenes like this

    Code (CSharp):
    1.     void Awake () {
    2.  
    3.         GameObject[] GameObject;
    4.        
    5.         GameObject= GameObject.FindGameObjectsWithTag ("TaggedObjects");
    6.  
    7.         foreach (var i in GameObject)
    8.            
    9.             Destroy (i);
    10.    
    11.     }
    12. }
    13.  
     
  5. aidanseeberg

    aidanseeberg

    Joined:
    Jul 10, 2015
    Posts:
    26
  6. TheIndieGuy

    TheIndieGuy

    Joined:
    Jul 17, 2015
    Posts:
    10
    Personally I'd create an object that manages these, something like MasterManager. Then have a script on this that checks if your DontDestroyOnLoad objects are spawned, if not spawn them. Using a manager would be better as you'd be able to keep track of how many are in the scene, destroy them, spawn them, edit them.
     
    phoda likes this.