0
0
Unityframework~10 mins

DontDestroyOnLoad usage in Unity - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to prevent the GameObject from being destroyed when loading a new scene.

Unity
void Awake() {
    [1](gameObject);
}
Drag options to blanks, or click blank then click option'
ADestroy
BDontDestroyOnLoad
CLoadScene
DInstantiate
Attempts:
3 left
💡 Hint
Common Mistakes
Using Destroy instead of DontDestroyOnLoad
Calling LoadScene inside Awake
Forgetting to pass the GameObject as parameter
2fill in blank
medium

Complete the code to ensure only one instance of the GameObject persists using DontDestroyOnLoad.

Unity
void Awake() {
    if (FindObjectsOfType<[1]> ().Length > 1) {
        Destroy(gameObject);
    } else {
        DontDestroyOnLoad(gameObject);
    }
}
Drag options to blanks, or click blank then click option'
AGameManager
BTransform
CRigidbody
DCamera
Attempts:
3 left
💡 Hint
Common Mistakes
Using a Unity component like Transform instead of the script class
Not checking the length of found objects
Not calling Destroy on duplicates
3fill in blank
hard

Fix the error in the code that tries to use DontDestroyOnLoad incorrectly.

Unity
void Start() {
    [1];
}
Drag options to blanks, or click blank then click option'
ADontDestroyOnLoad
BDestroy
CDontDestroyOnLoad(gameObject)
DDontDestroyOnLoad(this.gameObject)
Attempts:
3 left
💡 Hint
Common Mistakes
Passing 'this' instead of 'this.gameObject'
Calling DontDestroyOnLoad without parameters
Using Destroy instead of DontDestroyOnLoad
4fill in blank
hard

Fill both blanks to create a singleton pattern that uses DontDestroyOnLoad correctly.

Unity
public class GameManager : MonoBehaviour {
    private static GameManager [1];

    void Awake() {
        if ([2] != null && [2] != this) {
            Destroy(gameObject);
            return;
        }
        [2] = this;
        DontDestroyOnLoad(gameObject);
    }
}
Drag options to blanks, or click blank then click option'
Ainstance
BgameObject
Cthis
Dmanager
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for check and assignment
Using 'gameObject' instead of the static instance variable
Not making the variable static
5fill in blank
hard

Fill all three blanks to complete the code that prevents multiple instances and uses DontDestroyOnLoad.

Unity
public class AudioManager : MonoBehaviour {
    private static AudioManager [1];

    void Awake() {
        if ([2] != null && [2] != this) {
            [3](gameObject);
            return;
        }
        [2] = this;
        DontDestroyOnLoad(gameObject);
    }
}
Drag options to blanks, or click blank then click option'
Ainstance
CDestroy
DDontDestroyOnLoad
Attempts:
3 left
💡 Hint
Common Mistakes
Using DontDestroyOnLoad instead of Destroy to remove duplicates
Using different variable names for the static instance
Not making the variable static