|
发表于 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(&#34;MonoController&#34;);
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(&#34;123&#34;);
}
public void Update()
{
Debug.Log(&#34;TestTest&#34;);
}
}
public class Test : MonoBehaviour
{
void Start()
{
TestTest t = new TestTest();
MonoManager.GetInstance().AddUpdateListener(t.Update);
}
} |
|