How to do it in C#?
Two easy ways:
- Create one object flagged by DontDestroyOnLoad in a previous scene the executes only once.
- Use a static variable. Be careful where you initialize it (i.e in Awake or Start are not really a good idea in your case. Also, static constructors.
Or use PlayerPrefs, which is especially useful if you want to keep the value between plays.
1 Like
The variable needs to be serializable for its value to be preserved when saving and reloading your scene.
In Unity, your serializable variables will be visible for editing in the Inspector panel for that class.
All public c# variables are serialized automatically.
Private variables are not serialized by default, but can be forced to be serialized (and therefore visible in the inspector) using the ‘[SerializeField]’ attribute before the variable declaration.
For more info, read these docs: Unity - Scripting API: SerializeField