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

2

主题

5

帖子

10

积分

新手上路

Rank: 1

积分
10
发表于 2022-11-26 14:51:56 | 显示全部楼层
自我介绍

广东双非一本的大三小白,计科专业,想在制作毕设前夯实基础,毕设做出一款属于自己的游戏!
公共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);
    }
}
回复

举报 使用道具

1

主题

5

帖子

9

积分

新手上路

Rank: 1

积分
9
发表于 3 天前 | 显示全部楼层
佩服佩服!
回复

举报 使用道具

您需要登录后才可以回帖 登录 | 立即注册
快速回复 返回顶部 返回列表