在某一个类调用另一个类里的方法的时候,往往需要这个类的实例,这在繁复的项目中,往往没有那么方便,需要在这个类中不断的通过对象图语言导航到我们需要的地方。但如果使用事件机制的,在这个类里发起一个事件,在另一个类了处理这个事件,就可以不需要这个实例对象,就能完成。
这里有两杯水,怎样将这两个杯子里的水调换一下呢?你需要第三只空杯子。事件机制,说实话也是这个道理,当你找到第三只杯子的时候,你就会觉得,没有什么难的了。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Object = System.Object;
public class EventManager : MonoBehaviour
{
private static EventManager _instance;
/// <summary>
/// 发起事件的字典
/// </summary>
private readonly Dictionary<string, System.Object> _dicIssue = new Dictionary<string, Object>();
/// <summary>
/// 处理事件的字典
/// </summary>
private Dictionary<string, List<Action<Object>>> _handleDictionary = new Dictionary<string, List<Action<object>>>();
/// <summary>
/// 单例
/// </summary>
/// <returns></returns>
public static EventManager GetInstance()
{
if (_instance == null)
{
var go = GameObject.Find("game");
if (go == null)
{
go = new GameObject("game");
}