/// <summary> /// Register a callback method to invoke when the given event is fired. /// Several listener can be set for the same event. /// The listener react only for the current gameObject /// </summary> /// <param name="moduleEvent">The event which trigger the listener</param> /// <param name="listener">A method to call when the event is called</param> public void AddListener(ModuleEvent moduleEvent, Action listener) { if (!ListenerMap.ContainsKey(moduleEvent)) ListenerMap[moduleEvent] = new List<Action>(); var listenerList = ListenerMap[moduleEvent]; if(!listenerList.Contains(listener)) listenerList.Add(listener); }
// Use this for initialization void Awake() { // Bind listeners var moduleEvent = new ModuleEvent("TestModule", 1); var moduleEvent2 = new ModuleEvent("TestModule", 2); target.GetComponent<ModuleEventRaiser>().AddListener(moduleEvent, this.DebugTest); target.GetComponent<ModuleEventRaiser>().AddListener(moduleEvent2, this.DebugTest2); // Trigger event target.GetComponent<ModuleEventRaiser>().FireEvent("TestModule", 2); // Print 100 logs Debug.Log("Main Thread Info"); // Should print before or during the execution of DebugTest2() (DebugTest2 is asynch) target.GetComponent<ModuleEventRaiser>().FireEvent("TestModule", 1); // Should print after the 100 logs, the listeners are processed sequentially }