- Home /
Passing Data Through Scenes?
I'm working on a game that has a scene for the game, and a scene for the Game-Over menu, in the Game-Over menu it displays your score, and asks if you want to play again.
So, I keep the score from the player and move it to the next scene by having the same game-object in both scenes and using
void Awake()
{
DontDestroyOnLoad (this);
}
However, this is causing a problem where after switching back and forth through the scenes, there are multiple instances of this GameObject in both scenes.. (Because it doesn't destroy to keep that data) but this starts causing major problems.
How can I just keep ONE game object constant throughout multiple scenes?
You are trying to use a singleton approach, but only inmplementing half the singleton, where you have DontDestryOnLoad, but then no check to see if the object already exists in the scene. Search Unity Singleton for many examples here. And as described in the given answer. Also : http://clearcutgames.net/home/?p=437
Answer by Demigiant · Feb 15, 2014 at 01:57 AM
You don't really need a GameObject just to keep a score. You could simply use static classes that don't derive from MonoBehaviour.
Still, to keep a single instance of a GameObject, in your case you could add a static variable "instance" to your GameObject. During Awake, you check if instance is null. If it is, you reference the GameObject itself there, and go on. If not null, the GameObject destroys itself instead, since it means there's already another one.
static GameObject instance;
void Awake()
{
if (instance == null) {
instance = this.gameObject;
DontDestroyOnLoad(this.gameObject);
} else {
Destroy(this.gameObject);
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
save scene and load using binary file 1 Answer
Admob ads work but are on all scenes 4 Answers