Unity单例模式

发布时间 2023-12-26 19:30:37作者: ComputerEngine

单例模式通常用于生成单一管理者,例如假设游戏只能有一个玩家,那么就可以将玩家的控制器作为一个单例存在使用。或者场景控制,也可以作为一个单例来使用。

//BaseManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Singleton <T> where T:new()
{
    private static T instance;
    public static T GetInstance()
    {
        if(instance == null)
            instance = new T();
        return instance;
    }
}

public class MonoSingleton<T> : MonoBehaviour where T: MonoBehaviour
{
    private static T instance;
    public static T GetInstance()
    {
        return instance;
    }
    void Awake()
    {
        instance = this as T;
    }
}

逐步解释

public class Singleton<T> where T:new()
//使用<T>来扩大其泛用性,这样就可以直接利用这个基类建立其他单例。
//where T:new()做约束,强制要求其存在新建方法,否则后续instance = new T();无效
{
    private static T instance;
    //单例不应该被随意获取,保持为私有状态
    public static T GetInstance()
    //使用一个公有函数来对单例进行访问
    {
        if(instance == null)//单例为空
            instance = new T();//新建单例
        return instance;//返回单例,由于前面已经保证单例不为空,所以必有返回值
    }
}
//对于需要继承MonoBehaviour的单例,则会有一定的变化
public class MonoSingleton<T> : MonoBehaviour where T: MonoBehaviour
//仍然还是和Singleton类似,使用where强制约束当前类继承MonoBehaviour
{
    private static T instance;
    public static T GetInstance()
    {
        //由于MonoBehaviour保证了启动必加载,因此不存在单例为空的情况,因此可以直接返回单例
        return instance;
    }
    void Awake()
    {
        //直接转换其为T类型并赋值
        instance = this as T;
    }
}