- Home /
Restoring Static Variables after DontDestroyOnLoad
Hello everyone!
Since the day I realised I'd have to learn using DontDestroyOnLoad() I knew I'd mess up a lot of things. It seems to be one of the hardest Unity Scripting topics for me =(
So I have an object Alpha with multiple children in a scene 0 with other objects connected to Alpha via script references. Alpha has DontDestroyOnLoad check and also destroys duplicates in case scene 0 is reloaded in playmode more than once.
Every time I go to scene 1 and back to scene 0 I have all the objects on their places, but objects other than Alpha lose every reference to Alpha and his children. It is caused by the fact that newly created Alpha that belonged to reloaded scene 0 got destroyed. So I decided to change the script to opposite, destroying the old Alpha on reload.
The result was the opposite but still more preferable. After reloading scene 0 again all objects were on their places and all the references were completely fine. The problem is that the script attached to Alpha has static variables that become null for the reloaded Alpha if I destroy the old one.
Is there a way to restore those variables and keep the references untouched?
Answer by Mikilo · Aug 31, 2015 at 04:36 PM
There is many way to handle what you are using. It is called the Singleton pattern.
Something that must be unique no matter what, and optionally stays alive for ever and ever.
But first of all, I must suggest you to avoid static. There is plenty of topics about it in the Internet, and enough reasons to make you avoid it.
But anyway, about your problem. You can use PlayerPref to store and restore values between scene. It is a pretty easy way to do it.
You restore values in Awake() and store values in OnDestroy().
It was intended XD
But you should really care about static.
From my point of view, you should not use static if you don't how it works internally, deeply in its guts! This advice will make you do better code!
Anyway glad to help.