How to make something not destroy on load in Unity

We have many game objects that are common to all scenes like background music. So why destroy and load every time you change a scene? In this tutorial, we will see how not to load a new scene without destroying a game object. I am using Unity 2021.1.13 for this tutorial.

If you are completely new to scene loading check out our beginner guide to Unity scene management.

You can prevent an object from being destroyed using a single line of code

DontDestroyOnLoad(this.gameObject);

That’s it. It’s that simple but the execution needs some precautions.

  1. Add this line to the Start or Awake function of the game object you don’t want to destroy.
  2. Remember this object should not be a child object. If the parent is destroyed then the child gets destroyed too.
  3. If in some case you load the initial scene twice then there is a chance of two objects being spawned and not destroyed. The best way to avoid this is to load this object in the initial splash scene which is loaded only once in the game’s lifetime.

This is how the final code looks like

using UnityEngine;


public class Scenes_buttons : MonoBehaviour
{
    public GameObject background_music;
    

    void Start()
    {        
        DontDestroyOnLoad(background_music);
    }

If you don’t have a scene that loads only once then you can use the code below to destroy the duplicate game object.

public static GameObject background_music ;

 void Awake()
 {
     if(background_music){
         DestroyImmediate(background_music);
     }else
     {
         DontDestroyOnLoad(background_music);
         background_music = this.gameobject;
     }
 }

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading