实现一个单例MonoSys,外部调用它。
MonoSys自己维护一个MonoController。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MonoController : MonoBehaviour
{
public event Action ApplicationPauseEvent;
public event Action ApplicationQuitEvent;
public event Action UpdateEvent;
public event Action<Scene, LoadSceneMode> SceneChangedEvent;
private void OnEnable()
{
SceneManager.sceneLoaded += OnSceneLoaded;
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
}
private void OnApplicationPause(bool pauseStatus)
{
if (pauseStatus)
{
ApplicationPauseEvent?.Invoke();
}
}
private void OnApplicationQuit()
{
ApplicationQuitEvent?.Invoke();
}
private void Update()
{
UpdateEvent?.Invoke();
}
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
SceneChangedEvent?.Invoke(scene, mode);
}
}
public class MonoSys
{
private static MonoSys _instance;
public static MonoSys Instance
{
get
{
if (_instance == null)
{
_instance = new MonoSys();
}
return _instance;
}
}
private MonoController _monoController;
private MonoSys()
{
var parentGo = GameObject.Find("Singleton");
if (parentGo == null)
{
parentGo = new GameObject("Singleton");
UnityEngine.Object.DontDestroyOnLoad(parentGo);
}
GameObject go = new GameObject(nameof(MonoController));
go.transform.SetParent(parentGo.transform);
_monoController = go.AddComponent<MonoController>();
}
public Coroutine StartCoroutine(IEnumerator routine)
{
return _monoController.StartCoroutine(routine);
}
public void StopCoroutine(IEnumerator routine)
{
if (_monoController != null)
{
_monoController.StopCoroutine(routine);
}
}
public void AddApplicationQuitEvent(Action action)
{
_monoController.ApplicationQuitEvent += action;
}
public void RemoveApplicationQuitEvent(Action action)
{
_monoController.ApplicationQuitEvent -= action;
}
public void AddApplicationPauseEvent(Action action)
{
_monoController.ApplicationPauseEvent += action;
}
public void RemoveApplicationPauseEvent(Action action)
{
_monoController.ApplicationPauseEvent -= action;
}
public void AddUpdateEvent(Action action)
{
_monoController.UpdateEvent += action;
}
public void RemoveUpdateEvent(Action action)
{
_monoController.UpdateEvent -= action;
}
public void AddSceneChangedEvent(Action<Scene, LoadSceneMode> action)
{
_monoController.SceneChangedEvent += action;
}
public void RemoveSceneChangedEvent(Action<Scene, LoadSceneMode> action)
{
_monoController.SceneChangedEvent -= action;
}
public IEnumerator DelayCall(float delayTime, Action action, bool isRealTime = false)
{
var coroutine = DelayCallCoroutine();
StartCoroutine(coroutine);
return coroutine;
IEnumerator DelayCallCoroutine()
{
if (isRealTime)
{
yield return new WaitForSecondsRealtime(delayTime);
}
else
{
yield return new WaitForSeconds(delayTime);
}
action?.Invoke();
}
}
}
网友评论