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();
    }

}
相关推荐
大傻^4 分钟前
SpringAI2.0 Null Safety 实战:JSpecify 注解体系与 Kotlin 互操作
android·开发语言·人工智能·kotlin·springai
魑魅魍魉都是鬼18 分钟前
Java 适配器模式(Adapter Pattern)
java·开发语言·适配器模式
笨笨马甲19 分钟前
Qt MQTT
开发语言·qt
Fairy要carry38 分钟前
面试-Agent上下文过载、步骤混乱的问题
开发语言·python
程序员Ctrl喵1 小时前
异步编程:Event Loop 与 Isolate 的深层博弈
开发语言·flutter
liuyao_xianhui1 小时前
优选算法_两数之和_位运算_C++
java·开发语言·数据结构·c++·算法·链表·动态规划
IT猿手1 小时前
MATLAB模拟四旋翼无人机飞行,机翼可独立旋转
开发语言·matlab·无人机
代龙涛1 小时前
WordPress 主题开发指南:模板文件、函数与页面选型规则
开发语言·后端·php·wordpress
代码探秘者1 小时前
【大模型应用】6.RAG 场景下的向量+关键词混合检索
java·开发语言·人工智能·python·spring