Notifications
Article
Test Article - Observer
Published a year ago
63
0
Observer Pattern
This Article is just a Test and to fill the Percentage Bar in the Unity-Account Page. But For Some reason I don't want it to be completely empty so here is the Observer Pattern I use in my games
I use a Class "Model" which contains my Value This Model has an Action OnChanged which will be Invoked, when the Value changed:
public class Model<T> { public event Action<T> OnChanged; private T _value; public T Value { get { return _value; } set { if (value.Equals(_value)) return; _value = value; OnChanged?.Invoke(_value); } } }
Thanks to the event Keyword we don't need to worry about that the Action is Public
From there we can enhance our Model with some quality of features
Model<int> health = 100;
We want to directly initialize your Models like this. So we need to overload the = operator. So in the Model Class we add the following lines
private Model(T value) { _value = value; } public static implicit operator Model<T>(T value) { return new Model<T>(value); }
The static Method is actually our = operator and it excpects the Value of the type T. In our example T is int With the Constructor that also expects a value of type T we assign this to our value. Note, that the OnChange will not trigger with this, because we actually creating a new Model
If you want to trigger the OnChange event, you have to change the value and not the model!
health.Value = 99;
But before we change the Value we need to register a Callback Something like this:
health.OnChanged += hp => { if (hp == 0) { /* * Trigger Death */ } /* * Render Health Bar */ };
Stephan Knödler
Bachelor of Sience - Programmer
1
Comments