当前位置: 首页 > backend >正文

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

一、基本写法

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;//脚本挂载在游戏对象上,运行时赋值}
}

二、改进后

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class SingletonMono<T> : MonoBehaviour where T:MonoBehaviour
{// Start is called before the first frame updateprivate static T instance;public static T GetInstance(){return instance;}protected virtual void Awake(){instance = this as T;}
}
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的单例模式对象,需要我们自己保证它的唯一性,不要重复挂载一个脚本,否则它的唯一性就会被破坏。

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

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class SingletonAutoMono<T> : MonoBehaviour where T : MonoBehaviour
{// Start is called before the first frame updateprivate 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;}}

测试脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class NewBehaviourScript : SingletonAutoMono<NewBehaviourScript>
{public void Test(){Debug.Log(NewBehaviourScript.GetInstance().name);}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class Test : MonoBehaviour
{// Start is called before the first frame updatevoid Start(){NewBehaviourScript.GetInstance().Test();}}

http://www.xdnf.cn/news/20335.html

相关文章:

  • Python快速入门专业版(七):整数与浮点数:Python数值类型的运算与精度问题(附解决方案)
  • 项目中的一些比较实用的自定义控件
  • Python文件打包为EXE的工具v1.0
  • 《AI大模型应知应会100篇》第67篇 Web应用与大模型集成开发实践——1小时打造国产大模型智能客服系统
  • MySQL问题5
  • github上传步骤
  • 季度最强策略:年化247%,回撤10%,夏普比率3.79。附大小盘轮动策略python源代码。
  • Nestjs框架: 使用 CASL 库实现基于角色的权限控制(RBAC)与细粒度访问控制的实战演示
  • 【嵌入式C语言】七
  • 【IQA技术专题】 多尺度的transformer网络IQA:MUSIQ
  • GO语言的主要语法和特性
  • 跨平台游戏引擎 Axmol-2.8.1 发布
  • 突破反爬限制:动态IP轮换策略与实现
  • XXL-JOB源码分析(服务端)
  • “唐人街大赛第二届”题解
  • Spring Boot 3.x 的 @EnableAsync应用实例
  • 基于51单片机的信号发生器函数发生器设计
  • 存储卡备用区用尽,拷贝机设置坏块数量又有何意义?
  • hot100-贪心算法(附图解思路)
  • 项目升级--Nginx
  • 一种基于迁移学习的零样本故障诊断方法
  • WSL2环境下因服务器重装引发的SSH连接问题排查记录
  • fastapi通过sqlmodel连接Mysql实现crud功能
  • 如何进行神经网络的模型训练(视频代码中的知识点记录)
  • 2025最新超详细FreeRTOS入门教程:第一章 FreeRTOS移植到STM32
  • dp算法的种类
  • 制衣跟单高效管理软件推荐
  • linux 安全与防护,全方向讲解
  • 华清远见25072班I/O学习day6
  • Qt绘图功能学习笔记