observer pattern in unity3d
Can I have a way to know if I have a messages invoke many scripts,if the messages change ,all the invoke script will receive the change message?I have one idea in my mind just using observer pattern,but I don't know how to do it
Answer by cjdev · Aug 27, 2015 at 07:21 AM
Here is a simple explanation and example of the Observer pattern. And this is the official Unity tutorial on events that should give you some good groundwork on how delegates work so you can do what you want. While it's not exactly the Observer pattern, it's close and very much like what you want to do, so here's a basic custom event manager that you can use in a project from any class:
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
public enum EVNT { MyEvent1, MyEvent2, MyEvent3 };
public static class EventManager {
private static Dictionary<EVNT, Delegate> eventTable = new Dictionary<EVNT, Delegate>();
public static void AddHandler(EVNT evnt, Action action)
{
if (!eventTable.ContainsKey(evnt)) eventTable[evnt] = action;
else eventTable[evnt] = (Action)eventTable[evnt] + action;
}
public static void Broadcast(EVNT evnt)
{
Delegate d;
if (eventTable.TryGetValue(evnt, out d))
{
Action action = d as Action;
if (action != null) action();
}
}
public static void RemoveHandler(EVNT evnt, Action action)
{
if(eventTable[evnt] != null)
eventTable[evnt] = (Action)eventTable[evnt] - action;
if (eventTable[evnt] == null)
eventTable.Remove(evnt);
}
}
You would use this by calling EventManager.AddHandler(EVNT.MyEvent1, MyFunction);
in some class with a function named MyFunction and then in some other class (or the same one) you would call EventManager.Broadcast(EVNT.MyEvent1);
which would then execute MyFunction.