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?
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.
-
-
Nope. Just use the normal C# event. I won't risk using anything that would prevent Unity from cleaning up their Objects such as
Texture2D
. – Programmer Jun 24 '17 at 9:02 -
Why WeakEventManager would prevent Unity from cleaning up objects? References are weak. – Adriano Di Giovanni Jun 24 '17 at 9:05
-
Bad phrasing. I don't know if it would and have not done test on this. Using some certain features in C# will prevent Unity from freeing their Objects. This includes misusing delegates or using anonymous delegates with Unity Objects. I think you should run a test and verify that nothing goes wrong with
WeakEventManager
before using it in a full game. Re-read my answer. I added one for point forUnityEvent
. – Programmer Jun 24 '17 at 9:33 -
Jackson's blog post (the second link) was a thorough analysis on the topic. – gdbj Jun 24 '18 at 16:48
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.