Hello, I’m running into a problem that I have only been able to partly solve.
I have a SavedGameManager class (singleton) which has SaveToCloud and LoadFromCloud functions. I need to call these functions from multiple scenes in my game.
First I instantiated the class by attaching it to a GameObject in my main menu scene. So when the game initially starts up I could load the players game data. But in order to also be able to call the save and load functions from within other scenes I added DontDestroy to the class so It wouldn’t disappear when I switch between scenes.
This is all good for a compiled game that ensures starting from the main menu, but a really annoying side effect of this approach is that I cannot start any other scene directly in the unity editor when developing… the GameObject will not exist and when calling SavedGameManager.instance.Save() I’m getting the error: NullReferenceException: Object reference not set to an instance of an object.
Are there any way to insatiate the class and make it globally available to all scenes some how?
put an empty game object with your SavedGameManager script and put it on every scene. test this and share you script, maybe you did not add make the method shared on all classes using the static keyword.
If your “SaveToCloud and LoadFromCloud” functions dont need data, they could be static and do their job even without a singleton instance in the scene.
Also you could use a ScriptableObject, this way all objects that depend on this “singleton” data could directly reference it in any scene.
Or use multiple additive scenes, keep a global scene with global singletons loaded all the time, in the editor you would still need to reopen 2 scenes to use it (global and the scene you are working on).
These are pure-code solutions, do not put anything into any scene, just access it via .Instance!
If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:
public void DestroyThyself()
{
Destroy(gameObject);
Instance = null; // because destroy doesn't happen until end of frame
}
There are also lots of Youtube tutorials on the concepts involved in making a suitable GameManager, which obviously depends a lot on what your game might need.
And if you really insist on barebones C# singleton, here’s a Highlander:
I would like to avoid having to place a GameObject just for that in ever scene (100+ scenes…) I’s like to have a autoscaling and less error prone solution for this.
They do they are chaching a lot of data
Yay ! awesome man this is exactly what I need sweet - thanks a lot !