Can you create a custom 'OnEvent()' function?

Hey.

I’d like to know if it’s possible to create a custom event function that would be called on all the scripts it is declared once something happens.

Like this:

You have several scripts that will behave differently at a single event. Let’s say for when the player dies. You would declare OnPlayerDeath() inside all those scripts and make them do their specific routines.

When the player dies, OnPlayerDeath() is automatically called on all the scripts where it is declared.

That way you would not need to reference all those possibly dozens of different scripts inside the Player script, nor use Update() on every instance of those different scripts to constantly check if(playerIsDead) and consume unnecessary CPU processing power.

Is there a way one can do that?
If not in this specific way, what would be the best approach?

Thank you.

Yes you can, each script/object would need to subscribe to the event, unsubscribe when necessary.
This isn’t unity specific but implementation in c#.

Unity Tutorial

Tutorial #1

Tutorial #2

Tutorial #3

Tutorial #4

And on and on.