C#單例的寫法:
(1)私有化構(gòu)造方法
(2)內(nèi)建靜態(tài)實例
(3)公開靜態(tài)方法給實例做初始化
在Unity中的運用
private static Singleton msingleton;
//Unity中大多數(shù)情況下私有化方法并不有關(guān)鍵的作用赃梧,所以可以省略不寫
//默認構(gòu)造方法使為了給實例的對象付初始值滤蝠,在Unity中,實例的對象就是場景中的對象授嘀,很多組件需要我們?nèi)燧d物咳,所以默認構(gòu)造方法并不實用
Singleton()
{
}
public static Singeleton SingletonAtrribute{
get{
//如果msingleton為空,并沒有產(chǎn)生實例
if(msingleton==null){
//就先找到Singleton這個類
singleton=GameObject.FindObjectOfType(typeOf(Singleton)) as Singleton;
//如果沒有找到Singleton這個類
if(msingleton==null){
//新建一個GameObject
GameObject go= new GamaObject();
//并且給go添加Singleton組件
go.AddComponent<Singleton>();
}
}
return msingleton;
}
}
單例和泛型的結(jié)合:方便在一個項目中重復使用單例
public class MonoSlingleton<T>:MonoBehaviar
where T:Component{
private static T t;
public static T instance{
get{
if(t==null){
t=GameObject.FindObjectOfType(typeOf(T)) asT;
if(t==null){
GameObject go= new GamaObject();
go.AddComponent<T>();
}
}
return t;
}
}
}