Unity: Singleton DontDestoryOnLoad script false reference - c#

So I have this manager in my start scene with DontdesoryOnload, that managers all the UIs, etc. It follows singleton pattern, so if I go to scene 2 and come back to my start-scene, the first manager will remain the same, and the manager in the newly opened start-scene will figure that there's already a manager, and destroy itself.
From here let's call the Manager remains alive Manager-Singleton and the manager that is destroyed as planned Manager-Dead.
The problem I'm having is that the references in my Manager-Singleton seem to false-reference.
When Manager-Dead is destroyed as planned, if I access a public GameObject under my Manager-Singleton, it will show me an error. Where if I click on those References fields in Inspector, it will lead me to the correct Gameobject which not not destoryed at all.
MissingReferenceException: The object of type 'GameObject' has been destroyed, but you are still trying to access it.
However, if I avoid Manager-Dead from being destroyed, (So there will be two managers in one scene), the code worked just fine.
I know you might be thinking, if there are two managers in the scene, there might be a UI overlap so that I might be clicking on ManagerDead's Button, and accessing its References. So after I got back to the Start scene, I manually disable the ManagerDead. And it turns out ManagerSingleton is changing ManagerDead's UI !
I really couldn't figure out where it went wrong. Any suggestions would be appreciated.
Following is some of my codes in case they might be useful:
[RequireComponent(typeof(UIManager))]
[RequireComponent(typeof(DataManager))]
[RequireComponent(typeof(StateManager))]
public class Managers : MonoBehaviour {
private static UIManager _UIManager;
public static UIManager UI
{
get { return _UIManager; }
}
private static DataManager _DataManager;
public static DataManager Data
{
get { return _DataManager; }
}
private static StateManager _StateManager;
public static StateManager State
{
get { return _StateManager; }
}
public string debugString = "";
void Awake(){
//Only one dataControl obj is allowed to exist and pass along.
if (GameObject.FindObjectsOfType<Managers> ().Length > 1) {
Destroy (gameObject);
} else {
DontDestroyOnLoad (gameObject);
}
_UIManager = GetComponent<UIManager> (); //!!!!! This is a Singleton class.
_DataManager = GetComponent<DataManager> ();
_StateManager = GetComponent<StateManager> ();
}
}

Problem solved, the Component referencing part is what's causing the trouble, Since _UIManager etc is static, that means when component referencing is called in Awake function of Manager-Dead, it will refer those reference to the GameObjects Under it even after it's destroyed.
This results in the static _UIManager from Manager-Singleton will be referred to the Destroyed Gameobjects under Manager-Dead.

Related

Unity Audio Singleton Across Scenes

So I have a basic singleton that handles audio across scenes.
private void Awake() {
if (Instance == null) {
Instance = this;
} else {
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
}
Let's say this audio singleton is placed in Scene1, if I switch to Scene2 it seems to work. The only issue is if I start from Scene2, the audio no longer works. I'm guessing this is because the singleton is only created in Scene1 so there is no singleton reference in Scene2. I have tried making my singleton into a prefab so I can have them in each of my scenes which solves my issue of not having an existing singleton in Scene2 but if I switch scenes then it stops working.
Is there a way I can have an audio singleton that works even if I don't start at Scene1? I guess it doesn't have to be a singleton but that's what I have so far. I'm new to unity so I've only been looking up basic Unity tutorials.
Edit: The reason I want to start from Scene2 is because I want to test specific scenes.
You could probably use a lazy instantiation like e.g.
[RequireComponent(typeof(AudioSource))]
public class CentralAudio : MonoBehaviour
{
[SerializeField] private AudioSource _source;
public AudioSource Source => _source;
private static CentralAudio _instance;
public static CentralAudio Instance
{
get
{
// instance already exists -> return it right away
if(_instance) return _instance;
// look in the scene for one
_instance = FindObjectOfType<CentralAudio>();
// found one -> return it
if(_instance) return _instance;
// otherwise create a new one from scratch
_instance = new GameObject(nameof(CentralAudio), typeof(AudioSource)).AddComponent<CentralAudio>();
}
}
private void Awake()
{
// ensure singleton
if(_instance && _instance != this)
{
Destroy(gameObject);
return;
}
_instance = this;
// lazy initialization of AudioSource component
if(!_source)
{
if(!TryGetComponent<AudioSource>(out _source))
{
_source = gameObject.AddComponent<AudioSource>();
}
}
DontDestroyOnLoad(gameObject);
}
}
so now you can use e.g.
CentralAudio.Instance.Source.PlayOneShot(someAudioClip);
and the first time the instance will be created on demand.
You can use my Singleton template below. When declaring your class use "public class MyClass : Singleton<MyClass>". What you need to do, is have a scene like Bootstrap or Startup and this is where you place your singleton gameobjects. They should use some standard singleton code very similar to what derHugo posted except I would not instantiate the component if it's not found - it should show an error in the log instead. Usually my manager singletons have useful properties and arrays on them that are set in the inspector, so just creating a component like that would lose all that functionality.
Once you have your Bootstrap or Startup scene, you move it to the top of the load order in your Build scene list. You should have another singleton gameobject also in the Startup scene that then loads Scene1 or Scene2 or whatever you need. I make a singleton called GameManager that has a state machine and determines what scenes to load and know where we are.
Quite often it will load in a GameUI scene or multiple UI scenes, and you can load them additively. That way you break up your game and UI into multiple scenes for organization. It's also important for collaboration when working on a team to have multiple scenes since they tend not to merge easily. Quite often people want an Intro scene, so the GameManager will have different states and move between them loading the different scenes. Don't call the singleton SceneManager though, Unity already has a class named that way.
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T: MonoBehaviour
{
protected virtual void Awake()
{
if (instance != null)
{
Debug.LogError($"Duplicate Singleton: {name} of type {typeof(T)}, destroying self");
GameObject.DestroyImmediate(gameObject);
}
else
instance = gameObject.GetComponent<T>();
}
static bool doneOnce;
/// <summary>
/// Returns the instance of this singleton.
/// </summary>
public static T Instance
{
[System.Diagnostics.DebuggerStepThrough]
get
{
if (instance == null)
{
instance = (T)GameObject.FindObjectOfType(typeof(T)); // not really any point to doing this (it will fail), Awake would have happened but it's possible your code got here before Awake
if (instance == null && !doneOnce)
{
doneOnce = true;
Debug.LogError($"!!! An instance of type {typeof(T)} is needed in the scene, but there is none !!!");
}
}
return instance;
}
}
private static T instance;
}

How to set a GameObject active on one scene form a button click function on second scene that is loaded additive C#, Unity

I'm new to coding and Unity, I'm working on a simple click style game to learn the basics of both. I've created several scenes: MainMenu, UI, 1st level and 2nd level. After pressing 'Start' in main menu i'm loading UI and 1st level additively.
In UI layer I have a shop UI and other bits that I never want to unload. On the 1st and 2nd level i have the bits that i want to have only on those scenes.
So, what I'm trying to do is when i purchase an item or upgrade for the 1st level i want a GameObject (sprite) to be set as active.
What I've tried to do is to call a function in one script that is attached to GameObject in 1st level from script that is attached to a purchase button in UI scene, but from what I was able to understand from messing with it will set that game object active if it's assigned in the UI scene - so the whole thing is basicly pointless and i can do it much easier.
Code in script attached to GameObject in 1st level scene
public class Work_Button : MonoBehaviour
{
public GameObject hubert12;
public void Huberd()
{
hubert12.SetActive(true);
}
}
Code in script attached to GameObject in UI scene
public class Shop : MonoBehaviour
{
public GameObject buyHubertOnebutton;
public GameObject test;
public void UnlockHubert1()
{
if (Global_Cash.CashCount >= 20)
{
Global_Cash.CashCount -= 20;
buyHubertOnebutton.GetComponent<UnityEngine.UI.Button>().interactable = false;
Work_Button sn = test.GetComponent<Work_Button>();
sn.Huberd();
}
}
}
If you have any remarks anout how i've spit scenes or anything else they will be more than welcome!
Thanks!
There's something you need to be aware of, and that is that you can't reference an object from one scene, in another. You CAN reference the same Prefab though, but that's a slightly different issue.
One way I find effective is to do something like this:
public class Work_Button : MonoBehaviour
{
public GameObject hubert12;
public void Awake ( )
{
Shop.Register ( this );
}
public void Huberd ( )
{
hubert12.SetActive ( true );
}
}
Then you can have a Shop manager that has instance and static components.
public class Shop : MonoBehaviour
{
// Static variables
private static Work_Button _workButton;
// Instance variables
public GameObject buyHubertOnebutton;
public static void Register ( Work_Button workButton )
{
_workButton = workButton;
}
public void UnlockHubert1 ( )
{
if ( Global_Cash.CashCount >= 20 )
{
Global_Cash.CashCount -= 20;
buyHubertOnebutton.GetComponent<UnityEngine.UI.Button> ( ).interactable = false;
if ( _workButton != null )
_workButton.Huberd ( );
}
}
}
This works by having your button register with the shop. And because we're using the static variable here, we don't need to "find" the Shop object. The instance method UnlockHubert1 will check to make sure there is a button registered.
This represents just one of many ways to accomplish this. It's also the most basic of basic implementations. But as of right now I'm fond of this method. Extending this, you could store the registered items in a Dictionary collection, and you could do some cleanup/deregister when a button is destroyed (i.e. OnDestroy ).
The assumption here is that there is only one Work_Button in the scene, otherwise you'll need a way to differentiate them (i.e. a Dictionary with am identifier as the key).

Call object on other scene C#

I have this problem that I want to call an object from my first scene then call that object on my second scene . I tried doing this
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
and put it on the object I don't want to destroy then changed my scene on the
void Start(){
SceneManagement.LoadScene("Menu",LoadSceneMode.Single);
}
But it's not there on the heirarchy
Could someone help me out
EDIT:
Now when the next scene is loaded
The object I wanted is not there anymore. It is being destroyed
Create a persistent object
Create a preloader scene here you can place a splash screen or whatever you prefer but the important thing is loading things that should be persistent(maybe such as a network or gamemanager)
Create a script PersistentObject.cs and put the following code in it
private void Awake(){
DontDestroyOnLoad(this.gameObject);
}
Put this script on any object you initialize in the preloader
Access object from anywhere
If you want to access an object in another scene there are several ways but I will assume you do not have any specific reference to the object
So if we have a GameManager.cs and we created a Persistent cube in our preloader called Cube we can get a reference to the gameobject by saying GameObject cube = GameObject.FindGameobjectWithName("Cube");
Now you are able to do whatever you want by using cube
Write less, Do more with singletons
Creating a singleton will also be very useful as well
public static class Singleton<T>: MonoBehavior where T: MonoBehavior{
private static T instance;
//Notice the lower and upper case difference here
public static T Instance{
get{
if(instance == null){
instance = GameObject.FindGameObjectOfType<T>();
}
return instance;
}
}
}
You can then add this to your script make accessing properties easier and reduces the amount of code you have to write
public class Cube: Singleton<Cube>{
private string cubeName = "Jeff";
public void ChangeCubeName(string newName){
cubeName = newName;
}
}
To access this methods of this class you could now call the singleton from anywhere in your code
Example
public class GameManager: MonoBehavior{
private void Start(){
cube.Instance.ChangeCubeName("Joe");
}
}

how to make a c# script run at scene start in unity

I am doing a school project. I need to check the destroyed objects in my scene as soon as the scene starts. problem is I don't know how to make it load or where to attach the c# script.
public static class DestroyedObject {
static List<GameObject> objs = new List<GameObject>();
public static void Add(GameObject obj)
{
if(!objs.Contains(obj))
objs.Add(obj);
}
}
If you want it to run when you start the scene you need to attach it to a GameObject. Create empty and attach it as a component.
The code that you want to run on start should be in the:
void Awake
{
//Your code here
}
or
void Start
{
//Your code here
}
functions.
Start is called as soon as the class is instantiated and Awake is called when the scene is started. Depends where you want it in the call stack, but in your case i think it will do essentially the same thing.
I think what you're looking for is a way to "save" what objects have been deleted : you simply have to make your class inherit from MonoBehaviour and call DontDestroyOnLoad() so your object containing the script will exist between the scenes.
public static class DestroyedObject : MonoBehaviour
{
public static DestroyedObject Instance;
private static List<GameObject> objs = new List<GameObject>();
private void Awake()
{
if (!Instance)
{
Instance = this;
}
else
{
DestroyImmediate(gameObject);
}
DontDestroyOnLoad(gameObject);
}
public static void Add(GameObject obj)
{
if(!objs.Contains(obj))
objs.Add(obj);
}
public static List<GameObject> GetDestroyedObjects()
{
return objs;
}
}
Then you simply access your script using DestroyedObject.Instance.Add() or DestroyedObject.Instance.GetDestroyedObjects() (some people don't like this kind of design pattern but it has proven to be very effective when using Unity).
Also as #Sergey asked, why creating objects (on scene loading) in order to delete them afterward : you could do the revers operation (only instantiate the needed ones).
Hope this helps,
Can you describe what you are trying to achieve in total? Because it looks like your way is not the best way to do it ;).
If all you want to know is how to execute a script at scene start: create a script that inherits from MonoBehaviour (no need for static class), attach it to a gameobject in your scene, and thats it!
If you want to execute code as soon as the scene starts (and the gameobject is loaded), put your code in Awake() or Start(). You can read about the execution order of those functions here: https://docs.unity3d.com/Manual/ExecutionOrder.html
Making a script static means it will be active in all scenes and even before any scene is loaded.
Additionally, i would not recommend the use of static classes unless you really need them.

Cannot make button non-interactable through seperate script

I'm trying to make a button interactable after a certain scene (playing level) has been loaded. It's a button in a menu scene that represent the loaded scene itself (level selectable after playing it).
The problem is this: If the users passes a certain level, say level 1, level 2 gets loaded, and a static method gets called:
public static void AllowTut2()
{
Tut2Allowed = true; //public static bool initialised in this script
tutorial2.interactable = true; //tutorial2 is a button in the "menu scene"
}
To make it clear where the variables come from, this is part of the same script:
public class LevelSelectScript : MonoBehaviour {
public Button tutorial2;
public static bool Tut2Allowed = false;
//...some other variables
void Start ()
{
tutorial2 = tutorial2.GetComponent<Button>();
tutorial2.enabled = false; //more later on
///... some other code
}
}
Now the problem is this error: An object reference is required to access non-static member `LevelSelectScript.tutorial2' (refers to method AllowTut2).
It seems that I cannot change tutorial2.interactable trough the given static method (called in another script).
It basically says the button tutorial2 is non-static, therefore cannot use this in a static method.
Now if I make the button static, i.e. change
public Button tutorial2;
to
public static Button tutorial2;
then I have no way to assign the button object in the scene to this variable in the attached script.
Does someone perhaps know a solution to this problem?
Thanks in advance!
if you want to use static varaibles and also use inspector for assigning you can use singleton , here is where you can learn it

Categories

Resources