一个可供继承的单例组件模板类:
public class SingletonComponent<TComponent> : Componentwhere TComponent : SingletonComponent<TComponent>
{static TComponent _instance;private static TComponent GetOrFindOrCreateComponent(){// 双检索if (_instance == null){// 尝试在场景中查找已存在的组件_instance = FindObjectOfType<TComponent>();// 如果找不到, 则创建一个空对象, 并且挂载上组件if (_instance == null){GameObject gameObject = new GameObject();_instance = gameObject.AddComponent<TComponent>();}}return _instance;}public static TComponent Instance => GetOrFindOrCreateComponent();
}
因为 Unity 是单线程的, 所以在这里没有必要使用双检索
使用方式
例如你要创建一个全局的单例管理类, 可以这样使用:
public class GameManager : SingletonComponent<GameManager>
{// your code here
}
注意事项
尽量避免让 SingletonComponent
帮你创建组件, 因为它只是单纯的将组件创建, 并挂载到空对象上, 而不会进行任何其他行为. 如果你的组件需要进行某些初始化, 那么它可能不会正常.