Skip to content
Ilan edited this page Mar 6, 2024 · 10 revisions

/!\ Under construction /!\

The Problem

When coding, we often reference a script to another. For example, the MechaController script uses the Unity Rigidbody script and decides when the method function should be called. This works fine and is what is done most of the time. However, it creates a dependency between MechaController and Rigidbody, one needs the other to work. If we remove the Rigidbody script, the MechaController would not work as expected or even crash crash.

Of course, to avoid dependency, we can make the field nullable and check that it is assigned before using it. While it works, it is not very pretty. And worse, imagine a script A that relies on script B that relies on script C, which itself relies on the script A. This create a circular dependency.

This project have hundreds of file, if we are not careful, it could end up as a web with files dependent on another and another and another. And when we just wanted to test a single script, we end up forced to another 10 mores.

The solution

There are various way to tackle this problem but my favorite so far is definitely events.

An event is composed of two parts:

  • The subscriber: It listens to the given event and receive a notification when the event is triggered.
  • The emitter: Triggers the event. All the subscriber will receive the notification and handle the event as they wish.

To better understand events, let's make an analogy. As a user on social networks, you follow your favorite artist. When they publish a new art or song, you receive the notification because you are subscribed. If one day you decide to unsubscribe, you won't receive anything the notification if a new song is published. But other followers will! And both the artist and you will be able to keep living your life. And the best part: you can follow them again whenever you want!

Clone this wiki locally