头段时间做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”.
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- pqdy.cn 版权所有 赣ICP备2024042791号-6
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务