Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why choose UnityEvent over native C# events?

Tags:

c#

events

unity3d

I mean, UnityEvents are slower than the native C# events and they still store a strong reference to the receivers. So, the only valid reason I can find to use UnityEvents over native C# events is their integration with the editor. Am I overlooking something?

like image 631
Adriano Di Giovanni Avatar asked Jun 24 '17 08:06

Adriano Di Giovanni


People also ask

Is Unityevent a delegate?

Events in Unity are a special kind of multicast delegate and, generally speaking, they work in the same way as regular delegates. However, while delegates can be called by other scripts, event delegates can only be triggered from within their own class.

Are events slow unity?

Please note that it's not that unity events are slow it's delegates are very fast. I run same test in build a while ago and unity events is roughly 11x slower than delegate but both GetComponent and changing position are 4x slower than unity events and toggling game object activate state is 6-7 slower than that.


2 Answers

Am I overlooking something?

Nope, you are not overlooking anything. The only advantage and reason to use UnityEvent is that it allows you to use events in the Editor. That's for drag and drop people or those making Editor plugins.

Another advantage of UnityEvent is that it prevents the problem of Unity Object not being freed due to the misuse of delegates or using anonymous delegates with Unity Objects. Although they get freed when the main script that's holding them is destroyed. The reason for this is because UnityEvent is implemented with weak references therefore removing/minimizing this problem. These two things are still not worth it to use UnityEvent over native C# events.

You should always use native event and delegate over UnityEvent if you are not making an Editor plugin because of its fast performance and small memory usage. See this and this post post for more information.

like image 53
Programmer Avatar answered Sep 20 '22 00:09

Programmer


UnityEvent is mainly used with Unity UI system, because ugui need to serialize callbacks configuration in ui system, such as the button's OnClick callback.

Serialization is a most important feature in unity game engine, with c# builtin event system, you can't do serialize.

So if you work with unity UI System, you must use the UnityEvent, if you want to serialize callback function configuration, you must use the UnityEvent.

In other situation, just use the c# builtin event.

like image 37
liyonghelpme Avatar answered Sep 17 '22 00:09

liyonghelpme