- Home /
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.
Considering build size, code maintenance and ease to work with I'd suggest the built in Send$$anonymous$$essage.
I haven't run tests on either so I can't comment on speed of execution, but I don't believe it will be your bottleneck (I fear the Garbage Collector and the Dreaded $$anonymous$$ysterious Overhead more than anything else).
On side note, you can use UnityEvent. For comparision between C# event and UnityEvents see this article.
Answer by whydoidoit · Jun 29, 2012 at 08:26 AM
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
adding to this, if you can get any prime31 plugin's you could see how good c# events are handled, and ofc everything has its own limitations.
Answer by fafase · Jun 29, 2012 at 07:58 AM
http://answers.unity3d.com/questions/243876/efficiency-of-sendmessage.html
This thread has a quick benchmark that could answer your question.
Your answer
Follow this Question
Related Questions
How to add a custom message to the existing monobehaviour messages? 0 Answers
notify just gameobjects close to specific position 1 Answer
once again, Sendmessage VS Getcomponent! 1 Answer
Sending and Receiving Messages globally with BroadcastMessage / SendMessage 4 Answers
Can someone explain SendMessage to me? 3 Answers