- Home /
Should I initialize my Unity events?
Hello!
I am now doing
[SerializeField] private UnityEvent _onComplete = new UnityEvent();
However I haven't seen other people do it.
Is there a hidden meaning behind all this?
Answer by hexagonius · Dec 16, 2019 at 08:51 PM
Welcome to serialization. The fact that you do not need to initialize in this case is the [SerializeField] attribute. Unity, by default, creates an instance of the UnityEvent on deserialization. IF you were using a UnityEvent exclusively in code (without the attribute or the public modifier), you'd run into a NullRef unless you manually initialize.
I think, from Unity 2019.3 it was, with the new serialized references, you'll need to do the initialization, because the serializer will be capable of deserializing to null, unless it's not.
Funny thing. Unity editor warns me that the UninitializedEvent is not initialized and will be null... However it is not null and it works both from editor and from code.
public class SerializedEventTest : $$anonymous$$onoBehaviour
{
[SerializeField] UnityEvent UninitalizedEvent;
private void Awake() => UninitalizedEvent.AddListener(LogFunction);
void Update() => UninitalizedEvent.Invoke();
public void LogFunction() => Debug.Log("I am the event callback");
}
(Tested in Unity 2020.1.0a14.1541 Personal)
You IDE does not know about the serializer Unity is using. What you can do is:
[SerializeField] UnityEvent UninitalizedEvent = default;
to get rid of it.
Your answer
Follow this Question
Related Questions
How to change target of UnityEvent 3 Answers
EventTrigger / EventListener (what's the difference?) 0 Answers
Getting the number of event handlers on an object and checking for null 0 Answers
Correct way to send an event to a specific enemy 0 Answers
Button doesn't work when returning to scene (android) 1 Answer