I'm working on a game prototype: I have a Cell class which, given a mouse click on its collider, can raise an event that should be listened in two different modules: Camera and UI.
The Observer pattern implementation that I generally use follows this diagram:
But in this case it seems too tight and I don't see a simple way of adding such diverse observers explicitly to the Subject instance. So I tried to find a way to use the Observer pattern without the subject class keeping track of its observers, and the solution I found out is creating a C# static event raised from the Cell class:
public abstract class Cell : MonoBehaviour {
public delegate void CellClikedHandler(Cell cell);
public static event CellClikedHandler CellCliked;
// ...
private void OnMouseDown() {
CellCliked?.Invoke(this);
}
}
public class ShowHideUI : MonoBehaviour {
private void Awake() {
Cell.CellCliked += ChangeUIVisibility;
}
public void ChangeUIVisibility(Cell cell) {
//...
}
}
public class CloseUpCamera : MonoBehaviour {
private void Awake() {
Cell.CellCliked += FocusCameraOnCell;
}
private void FocusCameraOnCell(Cell cell) {
//...
}
}
I have it currently working this way, but it doesn't feel right. I read here that it's particularly important with static events to unsubscribe so that instances don't get rooted, but I'm not sure of any further implications.
So I was wondering: which is the usual approach to implementing the observer pattern without explicitly adding the observers to the subject instance? If static events are generally used in this way, are there any downsides to it?