unity单例模式的样板代码

2022-08-13  本文已影响0人  吉凶以情迁

using UnityEngine;

/// <summary>
/// A static instance is similar to a singleton, but instead of destroying any new
/// instances, it overrides the current instance. This is handy for resetting the state
/// and saves you doing it manually
/// </summary>
public abstract class StaticInstance<T> : MonoBehaviour where T : MonoBehaviour
{
    public static T Instance { get; private set; }
    protected virtual void Awake() => Instance = this as T;
    protected virtual void OnApplicationQuit()
    {
        Instance = null;
        Destroy(gameObject);
    }
}
/// <summary>
/// This transforms the static instance into a basic singleton. This will destroy any new
/// versions created, leaving the original instance intact
/// ///这将把静态实例转换成一个基本的单例。这将摧毁任何新的
///创建的版本,保留原来的实例不变
/// </summary>
public abstract class Singleton<T> : StaticInstance<T> where T : MonoBehaviour
{
    protected override void Awake()
    {
        if (Instance != null) Destroy(gameObject);
        base.Awake();
    }
}

/// <summary>
//最后,我们有了一个持久版本的单例。这将通过现场生存
/// / / 负载。非常适合需要有状态、持久数据的系统类。或音频来源
///通过加载屏幕播放音乐,等等
/// </summary>
public abstract class PersistentSingleton<T> : Singleton<T> where T : MonoBehaviour
{
    protected override void Awake()
    {
        base.Awake();
        DontDestroyOnLoad(gameObject);
    }
}

其中PersistentSingleton.DontDestroyOnLoad 是不会随场景变更而销毁,用于音频管理器。如果同一个节点下 存在单例模式,则会影响该节点所有脚本。

上一篇 下一篇

猜你喜欢

热点阅读