using System.Collections.Generic;
public class TestDelegate : BehaviourSingleton<TestDelegate>
{
public enum TestType
{
test1,
test2,
test3
}
public delegate void OnBroadcast(TestType type, params object[] objs);
private Dictionary<TestType, System.Delegate> messageEventTable = new Dictionary<TestType, System.Delegate>();
public void Subscribe(TestType type, OnBroadcast handler)
{
if (!messageEventTable.ContainsKey(type))
{
messageEventTable[type] = null;
}
messageEventTable[type] = (OnBroadcast)messageEventTable[type] + handler;
}
public void Unsubscribe(TestType type, OnBroadcast handler)
{
if (!messageEventTable.ContainsKey(type))
{
messageEventTable[type] = null;
}
messageEventTable[type] = (OnBroadcast)messageEventTable[type] - handler;
}
public void RaiseEvent(TestType type, params object[] objs)
{
if (messageEventTable.ContainsKey(type))
{
OnBroadcast handler = (OnBroadcast)messageEventTable[type];
if (handler != null)
{
Delegate[] list = handler.GetInvocationList();
bool hasNull = false;
foreach (Delegate dele in list)
{
if (dele.Target.ToString().Equals("null"))
{
handler -= (OnBroadcast)dele;
messageEventTable[type] = (OnBroadcast)messageEventTable[type] - (OnBroadcast)dele;
hasNull = true;
}
}
handler(type, objs);
}
}
}
}
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
// Use this for initialization
void Start () {
TestDelegate.Instance.Subscribe(TestDelegate.TestType.test1, ss1);
TestDelegate.Instance.Subscribe(TestDelegate.TestType.test2, ss2);
TestDelegate.Instance.Subscribe(TestDelegate.TestType.test3, ss3);
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.A))
{
TestDelegate.Instance.RaiseEvent(TestDelegate.TestType.test1);
}
if (Input.GetKeyDown(KeyCode.B))
{
TestDelegate.Instance.RaiseEvent(TestDelegate.TestType.test2);
}
if (Input.GetKeyDown(KeyCode.C))
{
TestDelegate.Instance.RaiseEvent(TestDelegate.TestType.test3);
}
}
void ss1(TestDelegate.TestType type, params object[] param)
{
Debug.Log("1111111111111");
}
void ss2(TestDelegate.TestType type, params object[] param)
{
Debug.Log("2222222222222222");
}
void ss3(TestDelegate.TestType type, params object[] param)
{
Debug.Log("3333333333333333333");
}
}