Reputation: 8482
I've been using Unity3D lately, and soon I discovered thorugh multiple topics online that using OnMouseUp event is much slower than checking for mouse clicks on the update() function. Can someone explain why is that?
Is that also valid for other on functions like OnTriggerExit2D and others? As a design pattern, should I abandon the on() functions completely and only catch events on Update()?
Upvotes: 2
Views: 1449
Reputation: 301
Agreed with the previous answer but as a reason to WHY the "On" functions are so much more inefficient lies in how they function.
How does unity know that an "OnMouseUp" event has fired? The mouse object would need to have an event handler attached to it that knows to fire the OnMouseUp event. Beyond that something would need to listen every single frame for that event and then run the required code. Also the OnEvent functions tend to get very dispersed because you could in theory have the same event in multiple different functions/classes.
I think the update method in general is a more efficient way to check, because there is a lot less overhead involved when you handle these things yourself.
tldr: There's more overhead involved in using the "On" events instead of in "Update"
Upvotes: 1
Reputation: 13146
I prefer neither of them but use the 'new' (since 4.6) Unity Event system when possible. In short you have to implement the appropriate handler interface like IPointerClickHandler.
I recommend to have a look at the Events tutorials, for example UI Events and Event Triggers. Note that although this tutorial is focussed on 2D, you can use the event system in 3D as well. You just need to add a Raycaster to your camera.
Upvotes: 1