前言:
首先介绍一下什么是单例,单例类和单例脚本
单例的标准形态:(也可以叫做单例类)
public class Singleton
{
private static Singleton instance;
public static Singleton Instance
{
get{
if(null=instance)
{
instance=new Singleton();
}
return instance;
}
}
}
通用模板的单例类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SingletonClass<T> where T : new()
{
//私有单例对象
private static T instacne;
public static T Instance
{
get
{
if (null == instacne)
{
instacne = new T();
}
return instacne;
}
}
}
那什么是单例脚本呢?其实就是继承了MonoBehaviour 的,能挂载在unity中运行的这么一个脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 单例脚本基类
/// </summary>
public class SingletonMono<T> : MonoBehaviour where T : SingletonMono<T>
{
private static T instance;
public static T Instance
{
get
{
if (null == instance)
{
GameObject obj = new GameObject(typeof(T).Name);
instance = obj.AddComponent<T>();
}
return instance;
}
}
protected virtual void Awake()
{
instance = this as T;
}
}
这是一个通用版的单例脚本,只要继承它的子类就可以通过里面的初始化,自动的实例出来使这个类成为单例脚本。
谨记:单例脚本千万不能挂载多次!可能会出现多种不同的bug
正文:
那么,什么是单例模式?
整个软件生命周期,某个类有且只能实例化一次,或者脚本只能运行一次;
比如说,对数据库连接和初始,各种管理类都需要使用单例,