For a small project Ive been working on, Ive been trying to figure out how to have a persistent scoring system carry from level to level (ex: you must have made a score of X in level one for the level 2 button in the main menu to unlock). Im not really sure how to do this though. I know it has something to do with DontDestroyOnLoad() but I havent been able to figure out how. Thanks in advance.
You have a few methods to do this:
- Use DontDestroyOnLoad: You create an object in the scene and add a script to it. In that script you call the DontDestroyOnLoad function, which prevents this object from being destroyed when a new scene is loaded. Then in your scene you search the hierarchy to see if the object exists. The problem with this is that if you want to do quick tests you probably want the same object in the scene without the need to pass the previous level, so you might end with 2 objects that do the same. This all leads to using a Unity’s Singleton (I don’t like singletons): Loading...
- Use a static class: You create a static class that stores the values, and on each scene you check those values accessing static methods and variables. A static class can’t be destroyed, so you’ll keep your values while loading the new level.
- Use PlayerPrefs or a file: This is similar to the static class, but instead of saving things in memory you save them somewhere else. It would be a requirement in the future anyway if you want to save the player’s progress.
Personally I would say some sort of encrypted or compressed save file, that way in the future the players’ data is saved between levels. Personally though (depending on your type of game) you might consider using a single scene. If it’s a high poly 3D game maybe not, but 2D games it works great. Scene’s in unity can be huge so you might consider just moving to a different position in the scene and using 1 level in different pieces. Thay way nothing has to be moved and/or reloaded and only progress needs to be saved.
You might want to check out this tutorial:
It’s very useful as it shows both how to use a singleton based on DontDestroyOnLoad, and how to properly save data between sessions.