头段时间做NGUI的时候,老大给我优化了很多,用到了C#的事件。由于我之前不是学C#的,下来花了点时间看了一下事件。我老大主要把事件用于对UI界面的切换。下面我们来看看代码吧。我的例子很简单的。
EventManager.cs
- using System;
- using System.Collections.Generic;
- public class EventArgs
- {
- }
- public class EventManager
- {
- static EventManager _instance;
- public static EventManager Instance
- {
- get
- {
- if (_instance == null)
- {
- _instance = new EventManager();
- }
- return _instance;
- }
- }
- public delegate void EventDelegate<T>(T e) where T : EventArgs;
- readonly Dictionary<Type, Delegate> _delegates = new Dictionary<Type, Delegate>();
- public void AddListener<T>(EventDelegate<T> listener) where T : EventArgs
- {
- Delegate d;
- if (_delegates.TryGetValue(typeof(T), out d))
- {
- _delegates[typeof(T)] = Delegate.Combine(d, listener);
- }
- else
- {
- _delegates[typeof(T)] = listener;
- }
- }
- public void RemoveListener<T>(EventDelegate<T> listener) where T : EventArgs
- {
- Delegate d;
- if (_delegates.TryGetValue(typeof(T), out d))
- {
- Delegate currentDel = Delegate.Remove(d, listener);
- if (currentDel == null)
- {
- _delegates.Remove(typeof(T));
- }
- else
- {
- _delegates[typeof(T)] = currentDel;
- }
- }
- }
- public void Raise<T>(T e) where T : EventArgs
- {
- if (e == null)
- {
- throw new ArgumentNullException("e");
- }
- Delegate d;
- if (_delegates.TryGetValue(typeof(T), out d))
- {
- EventDelegate<T> callback = d as EventDelegate<T>;
- if (callback != null)
- {
- callback(e);
- }
- }
- }
- }
EventArgs.cs
- using UnityEngine;
- using System.Collections;
- public class UIEventArgs : EventArgs {
- private bool _isOpen;
- public bool IsOpen
- {
- get
- {
- return _isOpen;
- }
- set
- {
- _isOpen = value;
- }
- }
- }
EventListener.cs(绑定在一个物体上)
- using UnityEngine;
- using System.Collections;
- public class EventListener : MonoBehaviour {
- // Use this for initialization
- void Start () {
- EventManager.Instance.AddListener<UIEventArgs>(OnReceive);
- }
- void OnReceive(UIEventArgs e)
- {
- if(e.IsOpen)
- {
- print ("Name:"+gameObject.name);
- }
- }
- }
SendEventMeg.cs (绑定在一个物体上)
- using UnityEngine;
- using System.Collections;
- public class SendEventMeg : MonoBehaviour {
- // Use this for initialization
- void Start () {
- }
- void Send ()
- {
- var arg = new UIEventArgs()
- {
- IsOpen = true,
- };
- EventManager.Instance.Raise(arg);
- }
- void OnGUI()
- {
- if(GUILayout.Button("Send"))
- {
- Send();
- }
- }
- }
结果:打印出“Name:xxxxx”.