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

}
相关推荐
电商API_180079052479 分钟前
获取淘宝商品视频API接口解析:通过商品链接url获取商品视频item_video
开发语言·爬虫·python·数据挖掘·数据分析
Pocker_Spades_A24 分钟前
Python快速入门专业版(五十):Python异常处理:try-except语句(捕获单一与多个异常)
开发语言·python
-可乐加冰吗1 小时前
SuperMap iObjects .NET 11i 二次开发(十五)—— 类型转换之面转点
visualstudio·c#·.net
hsjkdhs1 小时前
C++之友元函数与前向引用
开发语言·c++
ajassi20001 小时前
开源 C# 快速开发(十二)进程监控
开发语言·开源·c#
库库8391 小时前
Java微服务知识点详细总结
java·开发语言·微服务
txwtech2 小时前
第4篇 vs2019+QT调用SDK连接海康相机显示图片
开发语言·数码相机·qt
王嘉俊9252 小时前
Flask 入门:轻量级 Python Web 框架的快速上手
开发语言·前端·后端·python·flask·入门
做运维的阿瑞2 小时前
Python 面向对象编程深度指南
开发语言·数据结构·后端·python
木木子99992 小时前
Python的typing模块:类型提示 (Type Hinting)
开发语言·windows·python