tutorial singleton c# unity code example

Example 1: unity singleton pattern

#region Singleton

void Awake()
{
	if (instance == null)
	{
		instance = this;
	}
	else
	{
		Destroy(gameObject);
		return;
	}

	DontDestroyOnLoad(gameObject);
}

#endregion

Example 2: unity singleton

private static GameObject _instance;
	// Create an accessible reference to the singleton instance
	public GameObject instance
	{
		get
		{
			// Obtain singleton instance, check if one exists first
			if(_instance = null)
			{
				_instance = new GameObject();
			}
			return _instance;
		}
		set
		{
			// If an instance is not null, one already exists
			if(_instance != null)
			{
				// Check if instance IDs differ, if they do then destroy duplicate
				if (_instance.GetInstanceID() != value.GetInstanceID())
					DestroyImmediate(value.gameObject);
				return;
			}
			// If the passed instance is new (different), assign it
			_instance = value;
		}
	}
    
	private void Awake()
	{
		instance = this;
	}