using UnityEngine;
using System.Collections;
public class Singleton<T> : MonoBehaviour where T : Component
{
private static readonly object syslock = new object(); //我叫他线程锁
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
lock (syslock)
{ //锁一下,避免多线程出问题
_instance = FindObjectOfType(typeof(T)) as T;
if (_instance == null)
{
GameObject obj = new GameObject(typeof(T).Name);
//obj.hideFlags = HideFlags.DontSave;
//obj.hideFlags = HideFlags.HideAndDontSave;
_instance = (T)obj.AddComponent(typeof(T));
}
}
}
return _instance;
}
}
// 这是为了不要在切换场景时单例消失,可以删掉
public virtual void Awake()
{
DontDestroyOnLoad(this.gameObject);
if (_instance == null)
{
_instance = this as T;
}
else
{
Destroy(gameObject);
}
}
public static bool IsBuild
{
get
{
return _instance != null;
}
}
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
public class Button_config : Singleton<Button_config>
{
}
C# 单例
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 什么是单例一个类只允许有一个实例,在整个程序中需要多次使用,共享同一份资源的时候,就可以创建单例,一般封装成工具类...