【U3D简单框架】1.单例模式(普通单例,mono单例)

    技术2022-07-11  122

    自我介绍

    广东双非一本的大三小白,计科专业,想在制作毕设前夯实基础,毕设做出一款属于自己的游戏!

    单例模式基类

    目的: 通过代码设计,让某个对象在游戏中,永远只存在一份: 比如一个游戏玩家只有一份角色数据比如各个游戏模块,都只需要独立的一个控制器即可 约束了代码的调用方式,让其访问的时候指向唯一的对象: 而不是进行重复的创建对象,销毁对象对性能而言,减少了内存垃圾回收的频率,点点滴滴的优化,积少成多 通常有两种需求: 不需要继承mono,因为不需要用到生命周期: 通常用在数据实体上 需要继承mono: 要用到组件上的一些生命周期通常用在模块的控制器上 代码怎么写: singleton: 定义属性访问器instance用static进行声明,就可以基于类级别进行访问 MonoSingleton: 建议所有继承该类的脚本都挂载到同个对象上用bool变量来表示该对象是否在场景切换的时候销毁,然后监听场景变化的时间,做逻辑,根据布尔值将组件从物体上移除

    BaseSingleton.cs

    // where表示约束,需要这个T拥有一个无参构造函数才能作为泛型传进来 public class BaseSingleton<T> where T:new() { private static T instance; public static T Instance() { if (instance == null) instance = new T(); return instance; } }

    使用只需要继承即可 BaseSingleton

    // 使用 public class GameManager: BaseManager<GameManager> { }

    mono单例

    using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MonoSingleton<T> : MonoBehaviour where T: MonoBehaviour { static T instance; //有时候,有的组件场景切换的时候回收 public static bool destroyOnLoad = false; public static GameObject monoSingleton; public static T Instance { get { if (monoSingleton == null) { monoSingleton = new GameObject("monoSingleton"); DontDestroyOnLoad(monoSingleton); } if (monoSingleton != null && instance == null) instance = monoSingleton.AddComponent<T>(); return instance; } } //添加场景切换时候的事件 public void AddSceneChangedEvent() { SceneManager.activeSceneChanged += OnSceneChanged; } private void OnSceneChanged(Scene arg0, Scene arg1) { if (destroyOnLoad == true) { if (instance != null) { DestroyImmediate(instance); //立即销毁 } } } }

    使用:常规继承,如果要在切换场景的时候销毁,则需要在构造函数中把destroyOnLoad值设置为true

    public class TestMonoSingleton : MonoSingleton<TestMonoSingleton> { public TestMonoSingleton() { destroyOnLoad = true; } public void Test() { Debug.Log("MonoSingleton..."); } void Start() { AddSceneChangedEvent(); } }

    随便新建一个 test.cs

    void Start() { TestMonoSingleton.Instance.Test(); }

    因为 destroyOnLoad 值设置为true所以如果有切换场景操作, TestMonoSingleton 脚本会自动销毁,而不是销毁 GameObject

    Processed: 0.011, SQL: 10