单例模式我相信是全部设计模式之中运用最普遍的设计模式之一。设计模式
今天咱们就来看看在unity中如何使用单例模式,在unity中,咱们分两种单例,一种是继承monobehavior的单例,一种是普通单例。多线程
1.MonoBehavior单例学习
其实在unity中,若是脚本是继承monobehavior,那么使用起单例来更加简单。this
只须要在Awake()里面,添加一句instance = this;spa
using UnityEngine; using System.Collections; public class test2 : MonoBehaviour { public static test2 instance; // Use this for initialization void Awake () { instance = this; } // Update is called once per frame void Update () { } }
2.普通类的单例线程
using UnityEngine; using System.Collections; public class test2 { private static test2 instance; public static test2 Instance { get { if (null == instance) instance = new test2(); return instance; } set { } } }
那么问题也就来了,细心的读者会发现,若是项目中有不少个单例,那么咱们就必须每次都写这些代码,有什么办法能够省去这些没必要要的代码呢?有,那就是面向对象最重要的思想:继承。设计
今天咱们就来学习下,本身封装一个单例类,只要项目中用到单例的话,就从这个单例类继承,把它变成单例。对象
public class Singleton<T> where T : new() { private static T s_singleton = default(T); private static object s_objectLock = new object(); public static T singleton { get { if (Singleton<T>.s_singleton == null) { object obj; Monitor.Enter(obj = Singleton<T>.s_objectLock);//加锁防止多线程建立单例 try { if (Singleton<T>.s_singleton == null) { Singleton<T>.s_singleton = ((default(T) == null) ? Activator.CreateInstance<T>() : default(T));//建立单例的实例 } } finally { Monitor.Exit(obj); } } return Singleton<T>.s_singleton; } } protected Singleton() { }