Design Pattern: Observer
When we want a game object to have a certain behavior we usually take that game object and modify its parameters, whether it is the position or something else.
All of this works if I can directly access that game object previously or if we can find it with the appropriate calls.
This design pattern flips this situation on its head. we take advantage of events and make all the game objects that are affected respond to my event call and behave accordingly.
In my example, I simply change the color of some cubes but we can use them as we see fit. In the main class, I define an event and I decided that this event must occur every time I press the spacebar. This will allow all the game object listening to receive the notification that I pressed the space bar.
In a second script that I connect to my cubes, I’m going to write the behavior that the cube should have when it receives the notification that the event has been activated. First I have to put the cube in listening mode so I have to add it to my event. It is also very important to remove the elements when they should not listen anymore because it can cause errors and burden the memory.
this is the result