You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
using UnityEngine;using System.Collections;namespaceObserverPattern{publicclassGameController:MonoBehaviour{publicGameObjectsphereObj;//The boxes that will jumppublicGameObjectbox1Obj;publicGameObjectbox2Obj;publicGameObjectbox3Obj;//Will send notifications that something has happened to whoever is interestedSubjectsubject=new Subject();voidStart(){//Create boxes that can observe events and give them an event to doBoxbox1=new Box(box1Obj,new JumpLittle());Boxbox2=new Box(box2Obj,new JumpMedium());Boxbox3=new Box(box3Obj,new JumpHigh());//Add the boxes to the list of objects waiting for something to happen
subject.AddObserver(box1);
subject.AddObserver(box2);
subject.AddObserver(box3);}voidUpdate(){//The boxes should jump if the sphere is cose to origoif((sphereObj.transform.position).magnitude <0.5f){
subject.Notify();}}}}
```'
== A Solution
Removing the observer fromthe observed. This breaks a dependency (whichis what we want).
```c#
using UnityEngine;publicinterfaceIObserver{voidWatch();}
using System;using UnityEngine;publicclassObserver:IObserver{Colorvalue,polledValue;privateintgroup;privateScriptHomescriptHome;privateAction<Color>callBack;publicObserver(ScriptHomescriptHome,intgroup,Action<Color>Callback){this.scriptHome =scriptHome;callBack=Callback;this.group =group;
Watch();}publicvoidWatch(){polledValue= scriptHome.GetColor(this.group);if(!polledValue.Equals(value)){
callBack(polledValue);value=polledValue;}}}