How effective are events in unity3d?

Hi i am planning to write a framework for unity3d to make 2d game dev. simple and easy. i want to know which one of it is faster, “C# events” or “Unity’s SendMessage”. I know both are slow only but if i have to choose one which one should i prefer, taking into account, speed of execution, build size, code maintenance, ease to work with and other stuffs. please help me, I dont want to go wrong with the core itslef. And also suggest me any other event based method to do so, if both of these are not good.

C# events are not at all slow. Delegates known ahead of time are very fast indeed (faster than doing a transform.position in your code). C# events have a number of limitations - they keep the objects alive if you are not careful so you have to make sure you remove your handlers. SendMessage is fairly slow and doesn’t give you much flexibility around parameters - you certainly won’t have events that can cancel or modify an operation if you use them. It depends what you need.

Tips:

  • Don’t use anonymous methods to handle events (they are hard to remove and can create closures that hold lots of things open)
  • for performance cache things like transform in local variables (don’t believe doing transform. In a script is the same as accessing a variable)
  • remove handlers in OnDisable or OnDestroy

This thread has a quick benchmark that could answer your question.