So here’s the problem i encountered:
Think about saving data between scenes. Most people would recommend some kind of Singleton-like approach. I’m fine with that but let’s think about the following scenario:
- I have a scene with a few things that should persist between scene changes
- I save them in a list, containing their positions, other data and the name/buildindex of the scene they are in
- I switch scenes back and forth
- When I want to exit the game I store this list in a file, no problem here
- Let’s say I don’t like the name or the buildindex I assigned to that scene and therefore change one/both of them. Then I make a new build of my game.
- Now the data I saved points to a scene that does not exist anymore. In other words: I “lost” in-game progress
I’ve been thinking a lot about how to go about it but there doesn’t seem to be a good way of storing the data safely. Do I really have to set one name and make sure to never change it?
I don’t really understand the problem here. If things need to persist between scenes, you can mark them as dont destroy on load. Which will cause them to live in their own scene where all the other stuff that is marked as dont destroy lives.
The singleton like approach is pretty common, but singletons have a couple of problems. I usually go for a ServiceLocator/Provider pattern to solve this problem, with objects that need to be accessible from anywhere, singleton style. That way you only have 1 singleton, which is the ServiceProvider, which is also responsible for the lifetime of all services that are started.
Here’s a tutorial for one implementation of the pattern. Service Locator Design Pattern
To solve the problem with names changing, where you use the name of a scene as an identifier, i would look towards using something that doesnt change as an identifier. Either by using something generated by unity that you know doesn’t change ( for example the guid of an asset in editor ). For self generated non changing IDs i usually go for System.Guid.
It feels like you’re explaining two separate problems at once. The singleton/Service stuff is to solve the issue where you need classes that have an application wide lifetime, and are accessible from anywhere. Whereas the second problem is serialization of data to drive and how to handle persistence between game sessions.
Singletons don’t store data safely, they just make your working memory accessible from anywhere in the code.