【U3D/简单框架】4.公共mono模块

自我介绍

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

公共mono模块

  • 知识点:过场景不移除
  • 作用:让没有继承mono的类可以开启协程,可以Update更新,统一管理Update

创建 MonoController.cs

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

public class MonoController : MonoBehaviour
{
    public event UnityAction updataEvent;

    void Start()
    {
        DontDestroyOnLoad(this.gameObject);
    }

    private void Update()
    {
        updataEvent?.Invoke();
    }

    public void AddUpdateListener(UnityAction fun) 
    {
        updataEvent += fun;
    }

    public void RemoveUpdateListener(UnityAction fun)
    {
        updataEvent -= fun;
    }
}

别看这controller很短,但这个控制器很强大,因为继承了MonoBehaviour,那怎么使用这个控制器呢

创建 MonoManager.cs

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

/// <summary>
/// 1. 可以提供给外部添加帧更新事件的接口
/// 2. 可以提供给外部添加协程的方法
/// </summary>
public class MonoManager : BaseManager<MonoManager>
{
    private MonoController controller;

    public MonoManager()
    {
        GameObject obj = new GameObject("MonoController");
        controller = obj.AddComponent<MonoController>();
    }

    public void AddUpdateListener(UnityAction fun)
    {
        controller.AddUpdateListener(fun);
    }

    public void RemoveUpdateListener(UnityAction fun)
    {
        controller.RemoveUpdateListener(fun);
    }

    public Coroutine StartCoroutine(IEnumerator routine)
    {
        return controller.StartCoroutine(routine);
    }
}

可以扩充开启协程之类的方法,非常简单,打开StartCoroutine的源码复制粘贴一遍即可

在这里插入图片描述

可以看到这里封装了controller里面的addupdate和removeupdate的方法,更重要的是利用继承了Monobehaviour的性质,还能开启协程(没有继承monobehaviour的类不能享受开启协程的优待),关键的是该类并不需要继承monobehaviour

使用,我们创建一个 Test.cs

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

public class TestTest
{
    public TestTest()
    {
        MonoManager.GetInstance().StartCoroutine(Test123());
    }

    IEnumerator Test123()
    {
        yield return new WaitForSeconds(1f);
        Debug.Log("123");
    }

    public void Update()
    {
        Debug.Log("TestTest");
    }
}

public class Test : MonoBehaviour
{
    void Start()
    {
        TestTest t = new TestTest();
        MonoManager.GetInstance().AddUpdateListener(t.Update);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值