Consider the following Unity C# script attached to a GameObject. What will be the output in the console after loading a new scene?
using UnityEngine; using UnityEngine.SceneManagement; public class TestDontDestroy : MonoBehaviour { void Awake() { DontDestroyOnLoad(gameObject); Debug.Log("Object Awake"); } void Start() { Debug.Log("Object Start"); SceneManager.LoadScene("Scene2"); } void OnEnable() { Debug.Log("Object Enabled"); } }
Think about what DontDestroyOnLoad does to the GameObject when a new scene loads.
DontDestroyOnLoad keeps the GameObject alive across scene loads, so Awake and Start run once. OnEnable runs once when the object is enabled. The logs appear once.
Which of the following best describes the purpose of DontDestroyOnLoad in Unity?
Think about what happens to GameObjects normally when a new scene loads.
Normally, all GameObjects in a scene are destroyed when a new scene loads. DontDestroyOnLoad keeps the specified GameObject alive across scene loads.
Look at this code snippet. Why does the GameObject duplicate after loading a new scene multiple times?
using UnityEngine; using UnityEngine.SceneManagement; public class PersistentObject : MonoBehaviour { void Awake() { DontDestroyOnLoad(gameObject); } void Start() { SceneManager.LoadScene("Scene2"); } }
Think about what happens if the scene with this script is loaded multiple times.
Each time the scene loads, a new GameObject with this script is created and marked DontDestroyOnLoad, causing duplicates. To avoid this, check if an instance already exists before creating or marking DontDestroyOnLoad.
Which option contains a syntax error when trying to use DontDestroyOnLoad?
using UnityEngine; public class Example : MonoBehaviour { void Awake() { // Mark this GameObject to not be destroyed on scene load DontDestroyOnLoad(gameObject); } }
Check for missing punctuation in the code.
Option C is missing a semicolon at the end of the statement, causing a syntax error.
You want to create a GameObject that persists across scenes without duplicates. Which code snippet correctly prevents duplicates?
Think about how to check if another instance already exists before marking DontDestroyOnLoad.
Option A checks if more than one instance exists and destroys the duplicate, ensuring only one persistent GameObject remains.