Notifications
Article
如何在Unity里方便的创建单例类
Published 7 months ago
64
0
创建单例类
正常情况下,我们每创建一个单例类(继承自MonoBehaviour的那种),需要写如下代码:
public class XXXManager : MonoBehaviour { private static XXXManager _instance; public static XXXManager Instance { get { if (_instance == null) { _instance = new GameObject(typeof(XXXManager).Name).AddComponent<XXXManager>(); } return _instance; } } }
如果有很多单例在项目中,这段代码会充斥在每个单例类的头部,造成冗余。
幸运的是,C#的泛型类可以帮助我们解决这个困扰,只需要写一个泛型的单例基类:
public class ManagerBase<T> : MonoBehaviour where T : ManagerBase<T> { private static T _instance; public static T Instance { get { if (_instance == null) { _instance = new GameObject(typeof(T).Name).AddComponent<T>(); } return _instance; } } }
然后我们创建一个单例类并继承它
public class XXXManager : ManagerBase<XXXManager> { }
访问这个单例类:
var mgr = XXXManager.Instance;

Tags:
Zheng Liu
Unity Developer - Programmer
1
Comments