单例模式:
单例就是游戏从始至终存在的唯一的实例,只需要生成一次,并且到游戏结束才需要销毁。
C#中的单例模式
单例模式的实现通俗来讲就是通过在本类中创建一个自己的实例来实现。在unity当中,如果不需要使用到monobeheviour的话,可以使用这种方式来构建单例。
转载:http://blog.csdn.net/yupu56/article/details/53668688
namespace SingleTest
{
public sealed class SingleCla
{
private static volatile SingleCla instance;
private static object syncRoot = new object();
public static SingleCla Instance
{
//只读
get
{
//判断instance是不是空 是空就穿件一个实例
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new SingleCla();
}
}
}
return instance;
}
}
}
}
unity中的单例模式
MonoBeheviour和一般的类有几个重要区别,体现在单例模式上有两点。
第一,MonoBehaviour不能使用构造函数进行实例化,只能挂载在GameObject上。
第二,当切换场景时,当前场景中的GameObject都会被销毁(LoadLevel带有additional参数时除外),这种情况下,我们的单例对象也会被销毁。 为了使之不被销毁,我们需要进行DontDestroyOnLoad的处理。同时,为了保持场景当中只有一个实例,我们要对当前场景中的单例进行判断,如果存在其他的实例,则应该将其全部删除。
第一,MonoBehaviour不能使用构造函数进行实例化,只能挂载在GameObject上。
第二,当切换场景时,当前场景中的GameObject都会被销毁(LoadLevel带有additional参数时除外),这种情况下,我们的单例对象也会被销毁。 为了使之不被销毁,我们需要进行DontDestroyOnLoad的处理。同时,为了保持场景当中只有一个实例,我们要对当前场景中的单例进行判断,如果存在其他的实例,则应该将其全部删除。
using UnityEngine;
using System.Collections;
public class SingleModle : MonoBehaviour {
private static volatile SingleModle instance;
private static object syncRoot = new object();
public static SingleModle Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
SingleModle[] instance = FindObjectsOfType<SingleModle>();
if (instance != null)
{
for (var i = 0; i < instance.Length; i++)
{
Destroy(instance[i].gameObject);
}
}
}
GameObject go = new GameObject("_SingleMode");
instance = go.AddComponent<SingleModle>();
DontDestroyOnLoad(go);
}
}
return instance;
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
如果工程内存在多个单例就需要复制粘贴这些代码。为了避免复制粘贴可使用模版类:
using UnityEngine;
using System.Collections;
public sealed class SingleModle<T> : MonoBehaviour where T : MonoBehaviour
{
private static volatile T instance;
private static object syncRoot = new object();
public static T Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
if (instance == null)
{
T[] instance1 = FindObjectsOfType<T>();
if (instance1 != null)
{
for (var i = 0; i < instance1.Length; i++)
{
Destroy(instance1[i].gameObject);
}
}
}
GameObject go = new GameObject(typeof(T).Name);
instance = go.AddComponent<T>();
DontDestroyOnLoad(go);
}
return instance;
}
}
}
转载:http://blog.csdn.net/yupu56/article/details/53668688