using UnityEngine;
using UnityEngine.Events;
using System.Collections;
using System.Collections.Generic;
public class EventManager : MonoBehaviour {
private Dictionary <string, UnityEvent> eventDictionary;
private static EventManager eventManager;
public static EventManager instance
{
get
{
if (!eventManager)
{
eventManager = FindObjectOfType (typeof (EventManager)) as EventManager;
if (!eventManager)
{
Debug.LogError ("There needs to be one active EventManger script on a GameObject in your scene.");
}
else
{
eventManager.Init ();
}
}
return eventManager;
}
}
void Init ()
{
if (eventDictionary == null)
{
eventDictionary = new Dictionary<string, UnityEvent>();
}
}
public static void StartListening (string eventName, UnityAction listener)
{
UnityEvent thisEvent = null;
if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
{
thisEvent.AddListener (listener);
}
else
{
thisEvent = new UnityEvent ();
thisEvent.AddListener (listener);
instance.eventDictionary.Add (eventName, thisEvent);
}
}
public static void StopListening (string eventName, UnityAction listener)
{
if (eventManager == null) return;
UnityEvent thisEvent = null;
if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
{
thisEvent.RemoveListener (listener);
}
}
public static void TriggerEvent (string eventName)
{
UnityEvent thisEvent = null;
if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
{
thisEvent.Invoke ();
}
}
}
unity简单消息监听
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- Vue组件二-事件反馈 - 子组件向父组件发送消息,父组件监听消息 开始 Vue组件是学习Vue框架最比较难的部分...
- 在2016年初的时候,曾有媒体报道关于Unity准备推出中文版的消息,但是后来这个话题也就不了了之了。 但是在这次...
- 视频地址http://www.sikiedu.com/my/course/304平常我们写的一些脚本 下面是测试的...