- Home /
Use Events or function or any best way ??
I got what events are but when to prefer them ? So i want to ask
1.If i have a function in some other script attached to other game object .Then i should use event or function call. Which will be more efficient?
2.In case i have more then one function in diff scripts attached to different objects.I should only use events ? Is it the best way?
3.making every event static is safe????
Answer by whydoidoit · Apr 03, 2014 at 09:15 AM
It would be unusual to make all events static - that would imply that lots of handlers got called when any kind of event happened and you want to avoid that.
SendMessage/SendMessageUpwards/BroadcastMessage are all fine for infrequent events like clicks etc. These are good at calling a relevant function on many different scripts at once. They are slow for things that happen every frame, so should be avoided in that case.
A function call is good if you only want to call one thing on one script and you can know which script it is, or which base class. Therefore function calls are faster than events so long as you already have the GetComponent call cached, otherwise that will lose your benefit. Events are way more flexible.
So in general, static events are good for really system wide things, otherwise get the component and wire up the events directly. Make sure you unwire properly to avoid memory leaks though. Use SendMessage etc to avoid these pitfalls at the cost of performance, but such tiny performance costs can be ignored in infrequent events like mouse clicks and (potentially) collisions etc.