Introduction
DontDestroyOnLoad keeps an object alive when you change scenes in a game. This helps keep important things like player data or music playing without restarting.
DontDestroyOnLoad keeps an object alive when you change scenes in a game. This helps keep important things like player data or music playing without restarting.
DontDestroyOnLoad(gameObject);
void Awake() {
DontDestroyOnLoad(gameObject);
}void Start() {
DontDestroyOnLoad(this.gameObject);
}This script keeps the MusicPlayer object alive when you change scenes. It prints a message when it starts.
using UnityEngine; public class MusicPlayer : MonoBehaviour { void Awake() { DontDestroyOnLoad(gameObject); } void Start() { Debug.Log("Music player started and will not be destroyed on load."); } }
If you call DontDestroyOnLoad on multiple copies of the same object, you may get duplicates after scene loads.
Use a singleton pattern to avoid duplicates when using DontDestroyOnLoad.
DontDestroyOnLoad keeps objects alive across scene changes.
Call it in Awake or Start on the GameObject you want to keep.
Useful for music, game managers, and persistent data.
DontDestroyOnLoad in Unity?DontDestroyOnLoad doesDontDestroyOnLoad in a Unity script?gameObject in scripts.gameObject, which is correct. DontDestroyOnLoad(this); uses this (the script), which is incorrect. Options B and C use unrelated types.void Awake() {
DontDestroyOnLoad(gameObject);
}
void Start() {
Debug.Log("Object alive");
}
What will happen when the scene changes?void Start() {
DontDestroyOnLoad(this);
}
What is the problem and how to fix it?gameObject to pass the GameObject the script is attached to.DontDestroyOnLoad?Pass the test and this pattern moves unknown