当前位置: 首页 > 工具软件 > Mono > 使用案例 >

公共Mono模块

幸乐湛
2023-12-01

作用:让没有继承Mono的类可以开启协程,可以Update更新,统一管理Update

public class MonoController : MonoBehaviour {
    private event UnityAction updateEvent;

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

    void Update() {
        if (updateEvent != null)
            updateEvent();
    }

    // 给外部提供的添加帧更新事件的函数
    public void AddUpdateListener(UnityAction fun) {
        updateEvent += fun;
    }

    // 给外部提供的删除帧更新事件的函数
    public void RemoveUpdateListener(UnityAction fun) {
        updateEvent -= fun;
    }
}


// -----------------------------------------------------
public class MonoMgr : BaseManager<MonoMgr> {
    private MonoController controller;

    public MonoMgr() {
        // 保证了MonoController对象的唯一性
        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);
    }

    public Coroutine StartCoroutine(string methodName, [DefaultValue("null"_] object value) {
        return controller.StartCoroutine(methodName, value);
    }

    public Coroutine StartCoroutine(string methodName) {
        return controller.StartCoroutine(methodName);
    }
}
public class Test {
    public Test() {
        // 不继承MonoBehaviour的类不能直接使用StartCoroutine
        MonoMgr.GetInstance().StartCoroutine(TestWait());
    }

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

    IEnumerator TestWait() {
        yield return new WaitForSeconds(1f);
        Debug.Log("waitfor 1 second");
    }
}


public class TestMono :MonoBehaviour {
    void Start() {
        Test t = new Test();
        MonoMgr.GetInstance().AddUpdateListener(t.Update);
    }
}

 类似资料: