The title is pretty self explaining. I want to know how to create my own events (like Unity’s Start/Awake/Update/OnTriggerEnter, etc…).
Those are called messages. I’m not too familiar with messaging system, but I believe you use the broadcastMessage and sendMessage functions to set up your own.
There are a few techniques that you can use, and honestly we’d need more context to be able to give you a solid recommendation about which one is best for your situation.
It’s important to know that the system that Unity is using is probably the worst one to choose for this. It uses strings and System.Reflection to find the function it wants to call by name, and then calls it. This is pretty slow. This kinda works because Unity has been optimized and it doesn’t do this work every frame, but SendMessage/BroadcastMessage (the closest equivalent accessible to you) would do it every frame. So don’t use that one.
If Unity were written from scratch today, it would almost certainly use inheritance to call these events, and that’d probably be my first recommendation. In other words, the MonoBehaviour class would have:
virtual void Update() {}
And in your script you’d override it with
override void Update() {
And Unity would call that function.
(All of the classes written since the first version of Unity use inheritance for these kinds of messages, for example OnInspectorGUI in editor scripts, which is why I’m pretty confident in the above claim about what Unity would use if it were written today. I assume the only reason it still uses the system it does is because users would have to add the word “override” to hundreds of script files.)
Another option, very similar, is an interface. This basically consists of a defined set of public functions, and when you implement an interface, other classes will know that these particular functions exist and can be called. The biggest difference between an interface and an inherited class is that the class can include other data, while an interface is just public functions.
In either of those cases, you’d want to use something like GetComponentsInChildren(), and then loop through that to call the function you want.
Delegates and events are another option.