So, how the heck is "OnCollisionEnter" sent?

function OnCollisionEnter(col:Collision)
{
}

Whenever there’s a collision this function is called.

How is that done?

  1. It’s not reflection because that’s slow.

  2. It’s not that they scan (in some way) at compile-or-launch time, because you can add/remove components at runtime and all works perfectly.

Thanks!

Not having seen their source, it’s difficult to know exactly what they do, but if I were to venture a best guess, I’d say they’re probably using reflection. Summarized very briefly in this context, Reflection is a mechanism that allows you to search the contents of an assembly and look for “symbols”, that is, the names of classes and their members, such as methods.

The scripts we write do not result in an executable in and of themselves, but instead compile into an assembly (a .dll file) which Unity uses to build into an executable when you ask it to build a standalone. The executable constructed by Unity (and the Editor during development) likely use Reflection to browse this dll for all instances of MonoBehavior, and then use GetMethod(“methodname”) on all the supported built-in methods, such as Awake, Start, Update, OnCollisionEnter, OnMouseOver, etc. etc.

See this post from StackOverflow that contains an example of what Unity’s internal code might look like:

Notice that the example acquires an object of type MethodInfo which represents information about the compiled method, such as Update or OnCollisionEnter. If this object is non-null, it means it was able to find the requested method in the class, i.e. the user (us!) wrote an implementation of the method. Then it calls MethodInfo.Invoke when appropriate, such as once per frame if it’s Update, for example.

Edit:

Also notice that the search for methods using Reflection is string-based. This helps explain why it is so imperative to use the correct name for the built-in methods, that is, it will find and invoke method Update(), but not update(), and OnCollisionEnter(), but not OnColisionEnter().

They do it in AddComponent at runtime - just cache it and add it to the list of things to be processed.

They’ve got a list of rigidbodies being transferred to the PhysX, they have a list of methods to be called in each of the circumstances of collision. When PhysX says OnCollisionEnter they either invoke that C# list as a multicast delegate or they run through a List and call all of the individual delegates.

When you Destroy a component its methods are removed from the list, when you Add one it’s methods are appended.