3

I have used a custom (system) EventHandler I created:

public event EventHandler<T> OnItemSelected;

I am then assigning a custom anonymous function:

.OnItemSelected += (...) => {};

However I am pretty sure that it isn't cleaning itself and when my gameObject is destroyed this causes a memory leak. How can I prevent this ? Should I replace my EventHandler by a UnityEvent and use RemoveAllListeners ?

Scipion
  • 11,449
  • 19
  • 74
  • 139
  • 1
    Some say it's appropriate to register events in Unity MonoBehavior's `OnEnable()` and to unregister them in `OnDisable()` (via `-=`), but maybe someone else knows a better pattern for you. – Philipp Lenssen Jan 29 '20 at 21:59

1 Answers1

0

You can't!

Lambda expressions are as you say anonymous and therefore can not be unregistered since you can not address them!

If you need to remove them later - don't use lambdas but rather explicit methods like e.g. instead of

OnItemSelected += (T) => { ... };

rather explicitly use

private void HandleItemSelected(T value)
{
    ...
}

OnItemSelected += HandleItemSelected;

which now you can also remove using

private void OnDestroy()
{
    OnItemSelected -= HandleItemSelected;
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
  • Thanks for your answer. However, I am here to discuss how Unity can help me with this issue, not how to do in c#. – Scipion Jan 30 '20 at 09:10
  • 1
    @Scipion but ... Unity is based on c# and all your scripts will probably be c# .. so this is basically a question about c#. Which tool you want to use depends on you. I showed how you can remove the listener from the `EventHandler`. If you rather want to use `UnityEvent` there speaks nothing against it really. – derHugo Jan 30 '20 at 10:04