Custom events in MonoBehaviour

As many of you know there are custom events like OnClick, OnDrag, OnPress, etc. in NGUI toolkit (Example).

My question is: how do you add your own custom events to Unity’s MonoBehaviour just like ArenMook did. With the introduction of the Unity 4.3 I’m missing mouse events and I’d like to write my own small extention using raycasts and new 2d colliders but I don’t want to use C#'s way of making events since NGUI’s solution is way more convenient.

Thanks.

1 Answer

1

NGUI seems to use Unity’s built-in SendMessage feature to emulate how Unity calls methods with agreed-upon names (even if they’re private): Unity - Scripting API: GameObject.SendMessage

Note that SendMessage uses a feature in C# (and other languages) known as reflection. This feature allows a program to examine its own structure at runtime - types used, their members, their names, etc. It offers a runtime model of your source code.

Reflection, like most language features that involve “runtime” in their explanation, is often used where it is not needed and usually less efficient than the alternatives. I suggest learning to use C# delegates (such as events) rather than adding more reflection to what Unity already has built into it.

I've been using delegates before but from user's perspective they are less convenient (having to inherit a class with event logic that derives from MonoBehaviour instead of MonoBehaviour itself, and having to subscribe to all desired events in Awake() or Start()), what kind of efficiency drop are we talking about when it comes to reflection? Much lower performance?

–

The inefficiency generally won't be noticeable unless you use SendMessage in, say, every OnGUI invocation. But I understand reflection as one of the least efficient language features (I don't know figures), so if it lands in a performance bottleneck it'll hurt. I code defensively, so unless I have a good excuse I don't use it. But no, you probably won't notice the performance hit. Just be careful with it.

–