Home > OS >  Shouldn't singleton always be destroyed?
Shouldn't singleton always be destroyed?

Time:12-15

While I was developing a game with Unity, when I moved to a new scene, an error occurred in the existing singleton structured manager (ex: UIManager).

I turned off DonDestroyOnLoad of several managers to resolve the error.

 protected virtual void Init()
    {
        DontDestroyOnLoad(_instance);
    }

MonoSingleton Class was made into an abstract class, allowing DonDestroyOnLoad to be controlled like the code above.

However, I wonder if I can use Singleton without DonDestroyOnLoad while using this code.

CodePudding user response:

This is a problem caused by overlapping Singleton objects as the scene moves. Therefore, Awake is executed when the scene is moved, so if you already have an Instance, you can insert a code that erases what was in advance so that it doesn't overlap. Like the code below. you can solve this problem

public class MonoSingleTon<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance = null;
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                instance = FindObjectOfType<T>();
                if (instance == null)
                {
                    Debug.LogError($"{nameof(T)} No Object");
                }
            }
            return instance;
        }
    }

    public virtual void Awake()
    {
        DontDestroyOnLoad(gameObject);
        if(Instance != this && Instance != null)
        {
            Debug.Log("Instance Has Disployed, Destroy This");
            Destroy(gameObject);
        }
    }
}

CodePudding user response:

there are 2 cases 1 where you need your script to be inherited by the next scene and the case where you don't , Singleton helps you to create a one and only instance of your class/script for logical reasons.

    public static YourClass instance;
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(instance);
        }else
        {
            Destroy(gameObject); // destroy the gameObject
            //Destroy(this); destroy on the attached script
        }
  • Related