c# unity add singleton code example
Example 1: how to make a singleton in unity
void Awake()
{
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
}
Example 2: unity singleton
public class Example
{
public static Example Instance{get; private set;}
void Awake()
{
if(Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
} else
{
Destroy(gameObject);
}
}
}
Example 3: unity singleton
private static GameObject _instance;
public GameObject instance
{
get
{
if(_instance = null)
{
_instance = new GameObject();
}
return _instance;
}
set
{
if(_instance != null)
{
if (_instance.GetInstanceID() != value.GetInstanceID())
DestroyImmediate(value.gameObject);
return;
}
_instance = value;
}
}
private void Awake()
{
instance = this;
}