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

}
相关推荐
cjp56038 分钟前
001.Blazor简介
c#
threelab1 小时前
Three.js 咖啡杯烟雾效果 | 三维可视化 / AI 提示词
开发语言·javascript·人工智能
初心未改HD1 小时前
gRPC 与 Protobuf 实战指南
开发语言·golang
2zcode2 小时前
基于MATLAB的交通流量预测模型设计与实现
开发语言·matlab·交通流量预测
工程师0072 小时前
C# 程序集、IL、CLR 执行流程
c#·clr·il·程序集
早日退休!!!2 小时前
操作系统锁
java·开发语言
lsx2024062 小时前
Python 统计学基础与高级应用
开发语言
研究点啥好呢2 小时前
快手多模态算法工程师面试题精选:10道高频考题+答案解析
java·开发语言·人工智能·ai·面试·笔试
xxjj998a2 小时前
PHP vs C#:核心差异全解析
开发语言·c#·php
遗憾随她而去.2 小时前
Java学习(一)
java·开发语言·学习