Hi, I’m new to Unity and by far no coding expert, so I have a more general question on performance of event handling. Sorry if this has been asked before but I could not find any direct answer in the forums or docs.
Sometimes I’d find it much more practical if I could handle events in scripts instead of linking everything through the inspector with the onClick() or the EventTrigger component, mostly because I have to make sure no script reference gets lost along the way if I move or rename things.
I read up (or tried so) on how event handlers and delegates work in C# and as far as I understand there technically has to be also a main event loop present somewhere that waits for user input and dispatches the event until it gets handled by the appropriate event handler in the end (just generally ?! ;)).
And the update function is called every frame aka main gameloop.
So my actual question is: Is there any major disadvantage in “listening” for events in the Update() function of a script compared to using the event components in the inspector?
Let’s say If I have a rather simple 2D game, where just some objects react to a click. Would there be any difference in performance?
I’m not asking for a thorough explanation of how events in unity work but maybe someone could just explain the general difference and advantage/disadvantage of either way? That would be awesome. Thanks!
You can add listeners with scripts by using EventTrigger (Redirecting to latest version of com.unity.ugui). Simply set up your script and attach it to the relevant game object in your hierarchy.
Thanks! I didn’t know of these yet. The examples I searched for did never make use of them.
I’d still be interested in the general performance difference between doing something with Event Triggers and waiting for input in the Update() function =)
The EventSystem does send out most (if not all) in its own Update loop already;
https://bitbucket.org/Unity-Technologies/ui/src/4bccdca73cf7359bbdaa2a8181951a4ce38cdb7b/UnityEngine.UI/EventSystem/EventSystem.cs?at=5.3&fileviewer=file-view-default
You can have hundreds or even thousands of update loops running concurrently without noticeable performance problems, depending of course on what platform you’re on and what you’re doing in your loops. It’s more a question of design structure than performance, at least if you stay within reasonable object counts.
Do you want a centralized structure where all events come from one point, or do you wish to manage things separately.
I’d say the difference in performance is negligible.
I’m pretty sure the performance would be nearly identical.
Ah thanks guys! That’s exactly what I wanted to know. I was missing the part that everything goes through a general update loop already
how you solve this problem please