unity3d – What’s the proper way to Add and Remove EventListener in C# Unity?
Below are my two examples of how I register and unregister Unity Event Listener via C#.
However, I am not sure which one is “Correct”, and the real difference in terms of use case.
If I accidentally Add Listener twice, what’s the expected behaviour of my first case? Will it remove all the function with same function name?
Otherwise, will it be safer to use Case 2, register it as Action, and remove it when disabled?
Please advise me.
Just for example, I have an Example Function first.
private void ExampleFunction()
{
Debug.Log("just example");
}
Case One: simply add and remove the registered function in single line
private void OnEnable()
{
ExampleScript.ExampleEvent.AddListener(ExampleFunction);
}
private void OnDisable()
{
ExampleScript.ExampleEvent.RemoveListener(ExampleFunction);
}
Case Two: registered “UnityAction” for the event, and remove the “UnityAction”
private UnityAction exampleAction = null;
private void OnEnable()
{
ExampleScript.ExampleEvent.AddListener(exampleAction = () => { ExampleFunction(); });
}
private void OnDisable()
{
ExampleScript.ExampleEvent.RemoveListener(exampleAction);
}
The above examples were used in some of my archived projects, but not sure which one is the best and secure method.
Read more here: Source link
