public enum Game
{
START,
END
}
public class GuanChaZheBase
{
private static GuanChaZheBase instance;
public static GuanChaZheBase Instance
{
get
{
if (instance == null)
{
instance = new GuanChaZheBase();
}
return instance;
}
}
public Dictionary<Game, Action> m_EventTable = new Dictionary<Game, Action>();
/// <summary>
/// 添加事件
/// </summary>
/// <param name="Type"></param>
/// <param name="callBack"></param>
public void AddListence(Game Type, Action callBack)
{
if (!m_EventTable.ContainsKey(Type))
{
m_EventTable.Add(Type, null);
}
if (m_EventTable[Type] != null && m_EventTable[Type].GetType() != callBack.GetType())
{
Debug.LogError("添加的事件:" + callBack.GetType() + "与原有事件:" + m_EventTable[Type].GetType() + "冲突");
}
m_EventTable[Type] = m_EventTable[Type] + callBack;
}
public void RemoveListence(Game Type, Action callBack)
{
if (!m_EventTable.ContainsKey(Type))
{
Debug.LogError("没有事件码为:" + Type + "的事件");
}
else
{
if (m_EventTable[Type] == null)
{
Debug.LogError("当前事件为空");
}
if (m_EventTable[Type].GetType() != callBack.GetType())
{
Debug.LogError("要移除事件与原有事件类型不同");
}
}
m_EventTable[Type] = m_EventTable[Type] - callBack;
if (m_EventTable[Type] == null)
{
m_EventTable.Remove(Type);
}
}
public void Brodcast(Game type)
{
Action d;
if (m_EventTable.TryGetValue(type, out d))
{
Action callback = d;
if (callback != null)
{
callback();
}
else
{
Debug.LogError("广播事件错误");
}
}
}
}
观察者模式的使用
public class GameManager : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
private void OnEnable()
{
GuanChaZheBase.Instance.AddListence(Game.START, StartPanel);
GuanChaZheBase.Instance.Brodcast(Game.START);
}
public void StartPanel()
{
GameObject go = Instantiate(Resources.Load("StartPanel") as GameObject, FindObjectOfType<Canvas>().transform);
}
使用完以后一定要在OnDestroy或者OnDisable中移除事件