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

--

--

--

project manager by day, unity developer by night

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Do You Need to Test Everything?

How To Automate Your Development Process ?

Gaspar Nagy on How to Improve Development and Business with BDD Testing

What’s Going On Behind the Screens: Ergo Weekly Dev Update September 8th

6 Things I Wished I Knew Before I Started Coding

Technologies & Tools to Watch in 2020

OpenSslCryptographicException: error:1414D172:SSL routines:tls12_check_peer_sigalg:wrong signature…

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Andrea Alicino

Andrea Alicino

project manager by day, unity developer by night

More from Medium

Design Pattern: Command

Design Patterns: State Pattern

Unity Dev: From Prototype to Work of Art

2D Mobile: Designing Enemies Using Abstract Classes