Hey there, excellent question. For this specific case, the unit events are being called when they are invoked. When the server spawns the unit, the ServerOnUnitSpawned method is called. In that method, the event is invoked. Then all subscribers hear that event call and respond accordingly.
In general I like to think of events in two ways. Which can occur at different times or at the same time.
-
The first is that it is an event! If something is going to happen, and you want everyone to hear about it, best to make an event out of it. Other classes can then respond to that event it different ways, depending on their own classes. A unit dies for example. Your stats class handles that death one way, maybe your enemy gets some resources, that’s a different response. Maybe you have a progression class, that needs to respond with some XP or level up. Trying to organize each of those calls from the unit class would be very difficult, so you can invoke an event, and let each class handle it accordingly. This is especially applies to static events. It can be less confusing to make one call, and have all the other classes respond accordingly. You can avoid chains of method calls, with one method triggering another, triggering another.
-
The second way I think of it, is in terms of object oriented programming. This is a more concrete way of thinking about it. You want to separate out the behaviour of each class, and reduce the interdependencies. The movement class handles movement, the combat class handles combat, the health class handles health. By invoking an event, that class does not have to worry about who is listening, it can just call the event. Then if you make a change to one of the classes responding to the event, it will not affect the event call in anyway. The goal is too achieve modularity and reduce the chance of bugs or errors.
I often use events when I want to avoid circular dependencies. For example, the health class might call to the unit class to tell it, it has no health left. The health class is dependent on the unit class, because it needs to tell it about the health status. The unit in turn might be dependent on the health class. When there is no health, the unit stops attacking for example. If instead the health class had an event for no health, the unit can subscribe and listen for it. Now the unit would be dependent on the health class, but the health class would not be dependent on the unit class, ending the circular dependency. This could be very important because not all health classes might be units, even if all units have health.
Hope this helps!