Do we need to be worried about order the OnDead event listeners are triggered?

Both the Unit and UnitRagdollSpawner are listening to the HealthSystem.OnDead event. Just code execution wise, it seems like we don’t control the order those are fired in, but these are actually linked events. Would it be better to invoke the ragdoll instantiation from the Unit when it dies? Yes this is coupling events, but these events seem like they should be dependent.

We’re pulling info about the Unit about the transforms for instance, but I would think we don’t actually know if the unit still exists because the OnDead method may have been called on it already?

In my own implementation for instance. All I have Unit.HealthSystem_OnDead doing is calling the Unit.Die() method, where I actually handle whatever I need there. Without the tutorial, I would have though I need to get the UnitRagdollSpawner in the Unit script and call it from the Unit.Die() method.

Does this matter, am I missing something down the line, or am I getting off into the weeds?

Generally, with event listeners, we tend to prefer that the calling object not know or care if there are listeners or in what order they are called… This keeps the dependencies one way, the listener is dependent on the caller, but the caller is not dependent on the listener…

You are correct, in that if the Unit were to receive the HealthSystem.OnDead event before the UnitRagdollSpawner received it, then the Unit would already be marked for destruction, and the originalRootBone would automatically get a Missing Reference error, but as it turns out, this should never happen.

Events in an event queue are fired in the order in which they are subscribed, so if the UnitRagdollSpawner subscribes to the event before the Unit does, it will get the call first. The same is true the other way round, the Unit would get the call first if it subscribed first.

As it happens, we’ve engineered things so that the UnitRagdollSpawner will always get the first call. We subscribe to the event in Awake() in UnitRagdollSpawner, but we subscribe to it in Start() in Unit. On any given GameObject, Awake() is always called on all objects before Start() is called on all GameObjects.

Alternatives include changing the execution order of scripts (to ensure that UnitRagdollSpawner is always called before Unit), or putting a non-static OnUnitDead event on the Unit and have the RagdollSpawner subscribe to that event instead of the Health event. That event would then be fired at the beginning of the Unit’s event handler.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms