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

}
相关推荐
观无16 小时前
雷塞运动控制(DMC3800)C#基础应用案例分享
开发语言·c#
w-w0w-w16 小时前
C++中vector的操作和简单实现
开发语言·数据结构·c++
Larry_Yanan16 小时前
Qt安卓开发(一)Qt6.10环境配置
android·开发语言·c++·qt·学习·ui
froginwe1116 小时前
ionic-range:深度解析与最佳实践
开发语言
Z1Jxxx16 小时前
整除整除整除
开发语言·c++·算法
superman超哥16 小时前
自定义迭代器的实现方法:深入Rust迭代器机制的核心
开发语言·后端·rust·编程语言·rust迭代器机制·自定义迭代器
2501_9216494916 小时前
主流金融数据API对比:如何获取精准、及时的IPO数据
开发语言·python·金融·restful
superman超哥16 小时前
IntoIterator Trait的转换机制:解锁Rust迭代器生态的关键
开发语言·后端·rust·编程语言·rust trait·rust迭代器·trait转换机制
墨月白16 小时前
【QT】 Lambda 表达式
开发语言·qt
没有天赋那就反复16 小时前
JAVA length
java·开发语言·算法