Answers for "singleton unity"

C#
7

unity singleton pattern

#region Singleton

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

	DontDestroyOnLoad(gameObject);
}

#endregion
Posted by: Guest on July-14-2020
12

singleton unity

public class Example
{
public static Example Instance{get; private set;}

void awake()
{
if(Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
} else
{
Destroy(gameObject);
}
}

}
Posted by: Guest on April-14-2020
3

how to make a singleton in unity

void Awake()
 {
   if (instance == null)
     instance = this;
   else if (instance != this)
     Destroy(gameObject);
 }
Posted by: Guest on November-03-2020
0

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;
	}
Posted by: Guest on January-11-2021

C# Answers by Framework

Browse Popular Code Answers by Language