Improving our code with events
So far, we used Unity event functions to detect situations that can happen in the game such as Awake
and Update
. There are other similar functions that Unity uses to allow components to communicate with each other, as in the case of OnTriggerEnter
, which is a way for the Rigidbody to inform other components in the GameObject that a collision has happened. In our case, we are using if
statements inside the Update
method to detect changes on other components, such as GameMode
checking whether the number of enemies has reached 0. But we can improve this if we are informed by the Enemy manager when something has changed, and just do the check at that moment, such as with the Rigidbody telling us when collisions occur instead of checking for collisions every frame.
Also, sometimes, we rely on Unity events to execute logic, such as the score being given in the OnDestroy
event, which informs us when the object is destroyed, but due to the nature of the...