- Home /
Saving objects through scenes
Hello everybody, I've seen tons of questions about saving objects. I found two different ways to do it: singleton or script like that
public void Awake()
{
DontDestroyOnLoad(this);
if (FindObjectsOfType(GetType()).Length > 1)
{
Destroy(gameObject);
}
}
But if two different objects will have the same script, they both will be deleted when game'll be started.
In my case, I want several different objects to be saved through scenes. E.g. one insance of character class, and few managers. So, I can not just made character class singleton, or use script above to save different objects. What shall I do? thanks
Answer by fafase · Feb 24, 2018 at 07:05 PM
You need a combo of DontDestroyOnLoad and singleton type of pattern.
private static ObjectType instance;
void Start()
{
if(instance == null) // This is first object, set the static reference
{
instance = this;
DontDestroyOnLoad(this.gameObject);
return;
}
Destroy(this.gameObject);
}
So Start is only called once for all objects. First time this is called, instance is null so the first if statement gets called and this object is assigned to static instance, game object is set to DontDestroyOnLoad.
For any forthcoming call of Start for that type of object, instance is no longer null (because it is static so it is the same for all instances of the type). Since it is not null, the first statement is skipped and this duplicate item gets destroyed.
Answer by dishant27 · Feb 24, 2018 at 06:03 PM
public void Awake()
{
DontDestroyOnLoad(this);
}
In this way, all your characters would be saved through scenes.
It's clear
I'm just asking for a way to save exactly one instance of whole class And this way it will be duplicated, if I change scene twice
Then, singleton is the option. Only 1 instance of whole class will persist. Please follow the link to learn about it. https://unity3d.com/learn/tutorials/projects/2d-roguelike-tutorial/writing-game-manager