02.继承MonoBehaviour的单例模式基类

一、基本写法

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    private static NewBehaviourScript instance;
    public static NewBehaviourScript GetInstance()
    {
        return instance;
    }
    private void Awake()
    {
        instance = this;//脚本挂载在游戏对象上,运行时赋值
    }
}

二、改进后

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SingletonMono<T> : MonoBehaviour where T:MonoBehaviour
{
    // Start is called before the first frame update
    private static T instance;
    public static T GetInstance()
    {
        return instance;
    }
    protected virtual void Awake()
    {
        instance = this as T;
    }
}
cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : SingletonMono<NewBehaviourScript>
{
    private void Start()
    {
        NewBehaviourScript.GetInstance();
    }

    protected override void Awake()
    {
        base.Awake();
    }
}

继承了MonoBehaviour的单例模式对象,需要我们自己保证它的唯一性,不要重复挂载一个脚本,否则它的唯一性就会被破坏。

三、自动创建对象并挂载脚本的方法,不用手动挂载脚本,防止重复挂载

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SingletonAutoMono<T> : MonoBehaviour where T : MonoBehaviour
{
    // Start is called before the first frame update
    private static T instance;
    public static T GetInstance()
    {
        if (instance == null)
        {
            GameObject obj = new GameObject();
            //设置对象的名字为脚本名
            obj.name = typeof(T).ToString();
            GameObject.DontDestroyOnLoad(obj);
            instance = obj.AddComponent<T>();
        }
            
        return instance;
    }
    
}

测试脚本

cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : SingletonAutoMono<NewBehaviourScript>
{
    public void Test()
    {
        Debug.Log(NewBehaviourScript.GetInstance().name);
    }
}
cs 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        NewBehaviourScript.GetInstance().Test();
    }

}
相关推荐
疯狂的维修6 小时前
c#中public类比博图
c#·自动化
qq_172805596 小时前
Go 自建库的使用教程与测试
开发语言·后端·golang
久绊A6 小时前
Hydra-SSH 破解安全防范
开发语言·php
阿昭L6 小时前
c++中获取随机数
开发语言·c++
3壹6 小时前
数据结构精讲:栈与队列实战指南
c语言·开发语言·数据结构·c++·算法
悟乙己6 小时前
使用 Python 中的强化学习最大化简单 RAG 性能
开发语言·python·agent·rag·n8n
max5006006 小时前
图像处理:实现多图点重叠效果
开发语言·图像处理·人工智能·python·深度学习·音视频
RickyWasYoung7 小时前
【代码】matlab-遗传算法工具箱
开发语言·matlab
土了个豆子的8 小时前
03.缓存池
开发语言·前端·缓存·visualstudio·c#