DontDestroyOnLoad kept the old one. The scene made another.

The problem
Kept forever, made again.
public class GameManager : MonoBehaviour{ public static GameManager Instance; void Awake() { Instance = this; DontDestroyOnLoad( gameObject ); }}
It survives every scene change. Load the menu again, and its GameManager is created a second time.
The fix
The first one wins.
In Awake, if an Instance already exists, the newcomer destroys itself.
Instance exists?→Destroy( me )
none yet?→keep me
The fix in code
Check before you keep.
void Awake(){ if ( Instance != null && Instance != this ) { Destroy( gameObject ); return; } Instance = this; DontDestroyOnLoad( gameObject );}
The original keeps its state. The copy is gone before it does anything.
Watch out
Only root objects survive.
DontDestroyOnLoad only works on a GameObject at the top of the hierarchy.
- Root object
- kept between scenes
- Child object
- a warning, nothing kept
- The fix
- keep it at the root
The rule
Keep the first. Destroy the copies.
- A copy in Awake?
- Destroy it
- Otherwise
- Instance = this
- Then
- DontDestroyOnLoad