Unity C# Singleton?

I’m trying to make a simple singleton object, basically just exists and spams the console that it exists so I can confirm it works when switching scenes (using Application.LoadLevel(Scene)). This doesn’t work yet, the Debug.Log fails to continue when loading the new scene and I’m kinda stuck. All the examples I’ve seen for Singletons look similar to this, just kinda banging my head into a wall. Any ideas?

using UnityEngine;
using System.Collections;

public class SimpleSingleton : MonoBehaviour 
{
	private static SimpleSingleton instance = null;
	
	// Game Instance Singleton
	public static SimpleSingleton Instance
	{
		get
		{ 
			return instance; 
		}
	}
	
	private void Awake()
	{
		// if the singleton hasn't been initialized yet
		if (instance != null && instance != this) 
		{
			Destroy(this.gameObject);
		}

		instance = this;
		DontDestroyOnLoad( this.gameObject );
	}

	void Update()
	{
		Debug.Log( "SINGLETON UPDATE" );
	}
}

I have made my own custom singleton pattern which I use for my games. Its very easy to use. Here’s a code snippet which i would like to share with you.

#region SINGLETON PATTERN
public static BicycleHandler _instance;
public static BicycleHandler Instance
{
	get {
		if (_instance == null)
		{
			_instance = GameObject.FindObjectOfType<BicycleHandler>();
			
			if (_instance == null)
			{
				GameObject container = new GameObject("Bicycle");
				_instance = container.AddComponent<BicycleHandler>();
			}
		}
	
		return _instance;
	}
}
#endregion

P.S
BicycleHandler is the script name of my current script which will be used for any object to make it singleton. And "Bicycle is the object name of my GameObject. Replace them according to yours. After that you will be able to use your singleton object like:
scriptName.Instance.function();

Well one problem is I’m dumb, I had all my Singleton objects parented to a GameObject that wasn’t set to DontDestroyOnLoad… so that fixed pretty much everything. Yay for being a dumb dumb >.<

Also, the function Destroy does not destroys the game object instantly. From the documentation: “Actual object destruction is always delayed until after the current Update loop, but will always be done before rendering.”

So in your Awake you should put a return statement to avoid executing the whole function. Try this:

private void Awake()
{
   // if the singleton hasn't been initialized yet
   if (instance != null && instance != this)
   {
      Destroy(this.gameObject);
      return;//Avoid doing anything else
   }

   instance = this;
   DontDestroyOnLoad( this.gameObject );
}

I have developed two version of singleton , both can destroy the component on editor without use the attribue [ExecuteOnEditMode].

GameSingleton only can be added on first built scene and can’t be destroyed on load, persist all game.
Singleton can be added on any scene but is destroyed on load.
Obviously both only let one instance.

This is the Singleton sample:

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance;
    public static T Instance
    {
        get
        {
            if (instance == null)
                instance = FindObjectOfType<T>();
            if (instance == null)
                Debug.LogError("Singleton<" + typeof(T) + "> instance has been not found.");
            return instance;
        }
    }

    protected void Awake()
    {
        if (instance == null)
            instance = this as T;
        else if (instance != this)
            DestroySelf();
    }

    protected void OnValidate()
    {
        if (instance == null)
            instance = this as T;
        else if (instance != this)
        {
            Debug.LogError("Singleton<"+this.GetType() + "> already has an instance on scene. Component will be destroyed.");
            #if UNITY_EDITOR
            UnityEditor.EditorApplication.delayCall -= DestroySelf;
            UnityEditor.EditorApplication.delayCall += DestroySelf;    
            #endif
        }
    }

   
    private void DestroySelf()
    {
        if(Application.isPlaying)
            Destroy(this);
        else
            DestroyImmediate(this);
    }
}

The scripts are aviable on my gitHub, https://github.com/Brbcode/BrbAssets/tree/master/Singleton

Here you may find what you need (around 22 min): Recorded Video Sessions on UI - Unity Learn. Here he makes the background music a “DontDestroyOnLoad” object to have the the same instance of object in multiples scenes and give some tips to guarantee that we have only one instance of this object.

We have made a good Singleton implementation on Unity Community, please check it out, I am sure you will find it the best.

Hope this helps, thanks!