2022/2/22日志—单例模式基类模块

2022/2/22

单例模式基类模块

没有继承MonoBehaviour的单例模式

//1.C#中泛型的知识
//2.设计模式中 单例模式的知识
public class BaseManager<T> where T : new()
{
    private static T instanace;
    public static GetInstanace(){
        if(instanace == null){
            instanace = new T();
        }
        return instanace;
    }
}

继承MonoBehaviour的单例模式

如果把他添加到多个组件,就会破坏单例模式的唯一性

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//继承MonoBehaviour的单例模式要自行确定其唯一性,之后只需要在新的脚本里重写Awake就好。 
public class SingleText<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance;

    private SingleText(){
        //私有构造函数,防止破环单例模式唯一性
    }

    public static T GetInstance() {
        //继承了Mono的脚本 不能够直接new
        //只能拖动到对象上或者添加脚本的API AddCompenent去加脚本
        //U3D内部帮助我们实例化他
        return instance;
    }

    protected virtual void Awake() {
        instance = this as T;
    }
}

为了防止操作失误,可以让单例模式自己去添加GameObject,让他实现自动化,可以确保他的唯一性。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SingleAutoMono<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T instance;

    public static T GetInstance() {
        if(instance == null) {
            GameObject obj = new GameObject();
            //设置对象为脚本名字
            obj.name = typeof(T).Name;
            //防止场景切换时移除
            //单例模式存在在整个生命周期中
            DontDestroyOnLoad(obj);
            instance = obj.AddComponent<T>();
        }
        return instance;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值