Improving our code with events
So far, we used Unity event functions to detect situations that can happen in the game such as
Update. These functions are ways for Unity to communicate two components, 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
ifs inside Updates to detect changes on other components, such as
GameMode checking whether the number of enemies reached 0. But we can improve this if we are informed by the Enemy Manager when something has changed, and just do the check-in that moment, such as with the Rigidbody telling us the collisions instead of checking 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 event, it can be called in situations we don't want to add to the score...