设计模式的应用----单例模式(Unity)


博主主要是用Unity3D引擎开发的,所以学习设计模式一般就用在unity中,今天来简单说一下unity中单例模式的使用.

非继承MonoBehaviour

非继承MonoBehaviour就比较简单了一般可以将封装成带泛型约束的方式,让想要单里的类来继承就好了

实现

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Singleton<T> where T:new()//T 约束 只能是class类型的
{
    static T instance;
    public static T Instance
    {
        get {
            if (instance==null)
            {
                instance = new T();
            }
            return instance;
        }
    }

}

这里用的是很简单的写法,但一般来说是够用的,如果觉得不够细致可以参考此处.

使用

1.定义单例类

public class  TestSingleton:Singleton<TestSingleton>//
{
    public void MYFUNC() {
        Debug.Log("Singleton...");
    }
}

2.使用单例类

TestSingleton.Instance.MYFUNC();

继承MonoBehaviour

继承自MonoBehaviour的也是比较简单的,先看代码

实现

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 T Instance
    {
        get {
            if (MonoSingletonObject.MonoSingleton_Obj==null)
            {
                MonoSingletonObject.MonoSingleton_Obj = new GameObject("MonoSingletonObject");
                DontDestroyOnLoad(MonoSingletonObject.MonoSingleton_Obj);
            }
            if (MonoSingletonObject.MonoSingleton_Obj!=null&& instance==null)
            {
                instance= MonoSingletonObject.MonoSingleton_Obj.AddComponent<T>();
            }
            return instance;
        }
    }
    #region 转场是否销毁组件
    //有时候  有的组件场景切换的时候回收的
    public static bool destroyOnLoad = false;
    //添加场景切换时候的事件
    public void AddSceneChangedEvent() {
        SceneManager.activeSceneChanged += OnSceneChanged;
    }

    private void OnSceneChanged(Scene arg0, Scene arg1)
    {
        if (destroyOnLoad==true)
        {
            if (instance!=null)
            {
                DestroyImmediate(instance);//立即销毁
                Debug.Log(instance == null);
            }
        }
    }
   #endregion
}
//缓存一个游戏物体
public class MonoSingletonObject
{
    public static GameObject MonoSingleton_Obj;
}

这里面代码分为两部分,一部分是获取实例化的类,另一部分是对转场实例化类的处理.都是比较实用的.注释也比较详细,一看就懂.

使用

1.定义单例类

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

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

2.使用单例类

TestMonoSingleton.Instance.Test();//使用单例类
//另外也可以测试切换场景后是否销毁实例化.

好了,今天的内容就这么点,如果想更细致点可以去看视屏了解详情.更加透彻的了解.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值