1. 继承于MonoBehaviour(不随着场景切换而销毁)

  基类代码:

 using System.Collections;
using System.Collections.Generic;
using UnityEngine; /// <summary>
/// 单例模式基类,继承于 MonoBehaviour,不随场景切换而销毁
/// 在场景中新建空物体 DDOL,挂载 T 类继承 DDOLSingleton<T> 即可
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class DDOLSingleton<T> : MonoBehaviour where T : DDOLSingleton<T>
{
protected static T _instance = null; public static T Instance
{
get
{
if (null == _instance)
{
GameObject go = GameObject.Find("DDOL");
if (null == go)
{
go = new GameObject("DDOL");
DontDestroyOnLoad(go);
}
_instance = go.GetComponent<T>();
if (null == _instance)
{
_instance = go.AddComponent<T>();
}
}
return _instance;
}
}
}

  测试:

  新建空实体 DDOL,挂载脚本 GameManage。

  新建一个按钮,实现加载下一场景功能,测试是否随场景销毁而销毁。

  Hierarchy :

Unity 单例-LMLPHP

  GameManage 代码:

 using System.Collections.Generic;
using UnityEngine; /// <summary>
/// 单例
/// </summary>
public class GameManage : DDOLSingleton<GameManage> {
public void TestMethod()
{
Debug.Log("GameManage");
}
}

  测试代码:

 /// <summary>
/// 测试单例
/// </summary>
public class Test : MonoBehaviour { // Use this for initialization
void Start () {
GameManage.Instance.TestMethod();
} // Update is called once per frame
void Update () { } public void OnBtnClick()
{
SceneManager.LoadScene();
}
}

  效果图:

Unity 单例-LMLPHP

2. 不继承于MonoBehaviour(随着场景切换而销毁)

  基类代码:

 /// <summary>
/// 单例模式基类,不继承于 MonoBehaviour,随场景切换而销毁
/// 挂载 T 类继承 DDOLSingleton<T>,重载 Init 函数即可
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class Singleton<T> where T : class, new()
{
protected static T _instance = null; public static T Instance
{
get
{
if (null == _instance)
{
_instance = new T();
}
return _instance;
}
} protected Singleton()
{
if (null != _instance)
{
Debug.LogError("This " + typeof(T).ToString() + " Singleton Instance is not null !!!");
}
Init();
} public virtual void Init()
{ }
}

  此时 GameManage 代码修改为:

 /// <summary>
/// 测试 Singleton
/// </summary>
public class GameManage : Singleton<GameManage> {
public override void Init()
{
base.Init();
} public void TestMethod()
{
Debug.Log("GameManage");
}
}
04-28 07:07