- Home /
Big problem with a small singleton
In my initial scene (Scene_1) I have a gameObject called ApplicationBase, which I made into a singleton like so:
public class ApplicationBase_scr : MonoBehaviour
{
public static ApplicationBase_scr instance = null;
public GameObject[] players;
private void Awake()
{
if (instance == null)
instance = this;
else if (instance != this)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
}
When I enter Scene_2, everything is fine, but when I RETURN to Scene_1 from Scene_2 there are suddenly two pieces of Singleton for a short time - the initial singleton (which I "carried" from Scene_1 into Scene_2) gets destroyed and it gets replaced by the new singleton from Scene_1.
What I would like to do is the following: when I'm returning from Scene_1 to Scene_2, I would like to KEEP the singleton I carried initially from Scene_1 to Scene_2 and back to Scene_1. And need the new Singleton in Scene_1 destroyed.
Answer by PaxForce · Jan 26, 2017 at 12:13 PM
I sloved this problem myself with the help of Unity's official and awesome 2D Rouglike tutorial. I simply created a SingletonLoader_scr class, that instantiates all the singletons I need in runtime.
using UnityEngine;
using System.Collections;
public class SingletonLoader_scr : MonoBehaviour
{
public GameObject applicationBase;
void Awake()
{
if (ApplicationBase_scr.instance == null)
Instantiate(applicationBase);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612104854im_/https://answers.unity.com/themes/thub/images/avi.jpg)