UnityC#Unity笔记-泛型单例
Wang ChenHan单例模式
一个类只有一个对象(实例)叫做单例模式。适用于管理类。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
private static ClassName instance;
public static ClassName Instance{ get{ return instance; } }
void Awake(){ instance = this; }
ClassName obj = ClassName.Instance;
|
对于使用多个单例的场景,可以使用泛型单例基类
泛型单例基类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class ClassName<T> : MonoBehaviour where T : MonoBehaviour { private static T instance; public static T Instance{ get{ return instance; } protected virtual void Awake(){ instance = this as T; }
} protected virtual void OnDestory(){ instance = null; } }
|
基类继承
1 2 3 4 5
| public class ClassName1 : ClassName<ClassName1>{
}
|
访问单例类
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class Test : MonoBehaviour { public ClassName c1=null; public ClassName1 c2=null; void Start(){ c1 = ClassName.Instance; c2 = ClassName1.Instance;
} void Update(){
} }
|
普通csharp类实现单例
1 2 3 4 5 6 7 8 9 10 11
| public class Test1{ private static Test1 instance; public static Test1 Instance{ get{ if(instance == null){ instance = new Test1(); } return instance; } } }
|