Performance: DontDestroyOnLoad usage
This affects how game objects persist across scene loads, impacting memory usage and scene load performance.
void Awake() {
if (FindObjectsOfType<GameManager>().Length > 1) {
Destroy(this.gameObject);
return;
}
DontDestroyOnLoad(this.gameObject);
}void Awake() {
DontDestroyOnLoad(this.gameObject);
}
// No check for duplicates, so multiple instances accumulate after scene reloads| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| DontDestroyOnLoad without duplicate check | N/A | N/A | N/A | [X] Bad |
| DontDestroyOnLoad with duplicate check | N/A | N/A | N/A | [OK] Good |
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