Hi, I’m using a singleton design to keep the player profile persistent between scenes. I’m having a problem when I return to the main menu from a level.
Lets call my main menu scene A and a level in the game scene B.
in scene A I have about 30 or 40 different variables for different gameobjects, text components, image components etc. When I load scene B, I have some scripts which will access the static singleton and read data from it, the singleton persists through to scene B as expected however when I return to scene A all of the references to the variables in that scene are gone. I was expecting that scene A would load again and my menu would still have all of the references.
Here’s the code I’m using for the singleton…
public class GameController : MonoBehaviour {
public static GameController Controller;
void Awake () {
if (Controller == null) {
DontDestroyOnLoad (gameObject);
Controller = this;
} else if (Controller != this) {
Destroy (gameObject);
}
}
}
I’ve been reading about DontDestroyOnLoad but I’m having a bit of trouble wrapping my head around how to get over this one. A possible solution I’ve been thinking might be to not destroy the object when I go from scene A → B … but then have some sort of flag I can set up to destroy it when moving back to scene A (B → A). Does anybody have any thoughts or ideas on how I might implement such a solution? I welcome any other ideas.
Another thing to note is that I don’t actually need any of the data in the singleton object by the time I make it back to scene A (the main menu). By that time I’ve saved the gamer profile and if I could completely reload the scene , destroy the singleton and create a new instance when scene A loads, then I think that’d work perfectly. The logic inside the awake function is what I could really use help with.
Thanks everybody,
-Andrew
UPDATE :
I haven’t found a clean elegant solution to this, but I figure the solution would be to use another method in the first place so for now I’ve found a way around… What I initially wanted was to put some logic in the awake function to handle destroying the singleton when I returned to the main menu. So what I did was add a removeInstance() function to the gamecontroller class and then from my Racemanager script(the script which is linked to the button click to go back to the main menu, I simply call the Gamecontroller.controller.RemoveInstance() function and it runs Destroy(gameobject). So when I return to the main menu and there is no active gamecontroller object it just creates a new one… Seems to work…