- Home /
Does the Singleton GameObject need to be in all scenes where i need to access it?
I just implemented a Singleton script and attached it to a GameObject in the first scene of the Game. This Singleton just loads some data that can be used across all scenes. My question is, do i need to put this GameObject in all scenes where i need to access the Singleton? I tested this by trying to access the Singleton in a scene WITHOUT the GameObject and it seems to have worked just fine, but I'm not sure how this works: since i'm no longer in the scene that loaded the GameObject with the Singleton script, i shouldn't be able to access it because it has been discarded right? I tought it worked something like this: The script still acts like a Singleton, but i would need to add the GameObject to every scene where i need it.
Answer by logicandchaos · Mar 18, 2020 at 09:14 PM
Yes any monobehaviour must be present in the scene. If your singleton has an Update() then it won't be called, if you don't need Update and don't want it in the scene, you should look at using a scriptableObject instead of a monoBehaviour.
Yes i don't need Update method, i only need to load some data on Start and make that data available to all the scenes. Ok so according to you i will need put my GameObject with the Singleton script on every scene that i need correct? But how can i load that data only once? I noticed that if i put it on Start of the GameObject it is constantly loading my data on every scene.. and i don't want that. $$anonymous$$aybe just use a boolean on the singleton instance to make me know that it has already been loaded?
You can put the script on an object in the starting scene, then call DontDestroyOnLoad(gameobject);
and it will persist on scene change.
https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
Answer by Serge144 · Mar 19, 2020 at 06:17 PM
Ok here's the working code:
using UnityEngine;
public class StorageSingletonManager : MonoBehaviour
{
public static StorageSingletonManager instance = null;
private PlayerData playerData;
void Awake()
{
if (instance != null)
{
Destroy(gameObject);
}
else {
instance = this;
DontDestroyOnLoad(gameObject);
}
}
// Start is called before the first frame update
void Start()
{
playerData = StorageManager.loadPlayerData();
}
public PlayerData getPlayerData() { return playerData; }
}