//第1种实现方式
public class Singleton
{
private static Singleton Instance=null;
private Singleton(){}
public static Singleton GetInstance()
{
if(Instance==null)
{
Instance=new SingLeton();
return Instance;
}
return Instance;
}
}
//第2种方式
public class Singleton<T>
{
private static T Instance=null;
private static readonly object locker= new object();
private Singleton(){}
public static T GetInstance()
{
lock(locker)
{
if(Instance==null)
{
Instance=new T();
return Instance;
}
}
return Instance;
}
//第3种方式
public class Singleton<T>
{
private static T Instance=null;
private Singleton<T>(){}
public static T GetInstance()
{
if(Instance==null)
{
Instance=new T();
return Instance;
}
return Instance;
}
}
//继承MonoBehaviour
//第1种方式
public class Singleton<T> : MonoBehaviour
{
private static Singleton Instance=null;
public static T GetInstance()
{
get
{
if(Instance==null)
{
Instance=FindObjectOfType(typeof(Singleton)) as Singleton;
return Instance;
}
return Instance;
}
}
1
//第2种方式
public class Singleton<T> : MonoBehaviour
{
private static T Instance=null;
public static T GetInstance()
{
get
{
if(Instance==null)
{
GameObject go=GameObject.Find("DDOL");
if(go==null)
{
go=new GameObject("DDOL");
DontDestroyOnLoad(go);
}
Instance =go.GetComponent<T>
if(Instance==null)
{
Instance=go.AddComponent<T>();
}
return Instance;
}
return Instance;
}
}