DontDestroyOnLoad tutorial
- by Christian Engvall
- April 19, 2016
- 2
This is a simple DontDestroyOnLoad tutorial for unity3D. It is used to keep game objects alive during for example scene reloads. In this tutorial we will look at how to keep game music playing while reloading a scene.
This technique is used in Friendsheep. You can download or clone this tutorial from this repository on Github. This tutorial exists in the Assets/Examples/DontDestroyOnLoad/ folder.
1. New scene
Start of by adding a scene and create an empty game object in the scene. Then add an audio source and drag your music to the audioclip. I used a free stock song from JewelBeat in this example. Download it here.
The new game object is called MusicController.
2. Add script
Add a new script to MusicController with the same name and open it with you editor.
3. MusicController.cs
The class we just created will look like this:
using UnityEngine;
using System.Collections;
public class MusicController : MonoBehaviour {
public static MusicController Instance;
void Awake()
{
this.InstantiateController();
}
private void InstantiateController() {
if(Instance == null)
{
Instance = this;
DontDestroyOnLoad(this);
}
else if(this != Instance) {
Destroy(this.gameObject);
}
}
}
First we create a static instance variable of the type MusicController and call it Instance. It’s in this variable we will store the reference to our object and make it available to use from other objects.
In the Awake() method we call another method that is called InstantiateController(). And that is where the magic happens.
InstantiateController()
First we check if Instance is null, and if it is, we set instance to this, and runs DontDestroyOnload(this). Else we check if this != Instance, then we don’t want that gameobject and we Destroy() it.
Github commit from step 2 and 3
4. Reloading Scene
To make sure this works lets add a button that reloads the current scene. So start of by adding one. Right click in the Hierarchy pane and select UI -> Button.
ButtonController.cs will look like this. It uses SceneManager.LoadScene() to reload the current scene:
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class ButtonController : MonoBehaviour {
public void ReloadScene() {
SceneManager.LoadScene (SceneManager.GetActiveScene ().name);
}
}
Then add ReloadScene() as an onClick event to the button.
That’s it. Now you can reload your scene how many times you wan’t without the music restarting. You can combine this tutorial with toggling music on and off.