- Home /
Persisting player when loading levels
I am learning unity with a simple learning project, a basic moon patrol clone. Everything was going great until I decided to add some features that require persistence when loading a level, specifically lives and respawning at checkpoints. At first I thought it would be simple, just add DontDestroyOnLoad to the Awake() function but I found that this resulted in an additional player after every death (Oddly stacked on each other vertically). I tried making the class static but I could not because it inherits from MonoBehavior and it wont allow that with an abstract class. I then tried creating a game manager class with just the variables I needed and not inheriting but then I get a warning that the script cannot be loaded because it is abstract. I am thinking I need to have the script not attached to a GameObject but cannot see how.
I have written c# before but the Unity3D way of having a ton of little scripts spread all over make it hard for me to manage the architecture of my code.
Answer by Kiwasi · Jun 20, 2014 at 01:16 AM
You can use DontDestroyOnLoad and the singleton pattern to ensure you don't get multiple copies of the same gameObject.
You can use static variables. Statics belong to the class and persist between scenes.
You can also create static classes that are not MonoBehaviours.
Then of course there is the tutorial on persistance if you get really stuck.
Without seeing your code its hard to pick exactly what works best.
You would think with all the googling I did I would have found that video. It has a method of doing a singleton that worked great in my case. I need to get used to the idea that in Unity3D a Singleton is not an anti-pattern. Thanks!!!!
BTW I will up vote this answer once I get enough reputation, I guess rep does not carry over like on most Stack Exchange sites.
Your answer
![](https://koobas.hobune.stream/wayback/20220613152006im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How can I flip only my 'Player' gameobject, and l leave it's child object alone? 2 Answers
Flipping a 2D Game object over time 1 Answer
Jumping from special jump orb 1 Answer