Events += in start without -=?

So Sam does a lot of event bindings in Start methods without unbinding it later on (not neccesarily in this course).
From what i know common practice is to bind them in OnEnable and then unbind them in OnDisable.

Does it matter? Does skipping unbinding not lead to memory leaks?

1 Like

If the publisher outlives the subscriber, yes, it might cause memory leaks, but if it doesn’t, then no, there won’t be any memory leaks whatsoever.

Basically you want to be sure to unsubscribe if the publisher is a singleton, also if the subscriber will get destroyed or disabled before the publisher, otherwise it will not only have a memory leak but an error, your game simply won’t work, that’s why is common practice to unsubscribe, but it’s not 100% necessary.

1 Like

A danger far greater than memory leaks lies in what happens if the event is raised and the component no longer exists.

As a rule of thumb:

  • Something that stays in the scene until the scene is changed doesn’t need to unsubscribe unless the event is on a Singleton or static.
  • If you need to subscribe and unsubscribe, use the corresponding pairs Awake or Start() → Unsub in OnDestroy. OnEnable → OnDisable
1 Like

In the topic of event unbinding - do lambdas unbind themself or they need to have action taken on them somehow.

Lets say i do

//class 1
public class Foo
{
    public static event Action onAddThings;
}
//class 2
public class Bar
{
    int i = 0;
    void OnEnable() => Foo.onAddThings += () => ++i;
}

and lets say i enable and disable object 20 times. Will there be only one event and i would increase only once?

Don’t do it. You can’t (you can, but it’s not nice) unsubscribe lambdas. See here:

1 Like

Aaaaaaaaaaaaand … one more on a topic :smiley: .

In the dialogue course (i don’t remember now if I or Sam did this) i ended up with code like this:

//BuildChoiceList() - called on every player dialogue ui
///...
button.onClick.AddListener(() =>
{
    _playerConversant.SelectChoice(choiceNode);
});

Is it equally as bad binding lambdas in OnEnable (lambda is passed as UnityAction)?

I think it will be if you need to remove the listener again because you have no reference to the lambda, and you need the reference to remove it. Same as events

1 Like

This wasn’t a problem because the button will be destroyed and the Lambda will just go away with the button. If, however, you were pooling, the Lambda is not the way to go.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms