Search Unity

Question When I sub a method to a Unity Button OnClick event, do I need to unsubscribe it as well?

Discussion in 'UGUI & TextMesh Pro' started by Entikai, Dec 27, 2020.

  1. Entikai

    Entikai

    Joined:
    Mar 22, 2020
    Posts:
    17
    When I sub a method to a Unity Button OnClick event, do I need to unsubscribe it as well via code?
     
  2. kuailemario

    kuailemario

    Joined:
    Mar 19, 2020
    Posts:
    25
    According to my experience, when using Lua code to register the listener, you must cancel the listener, otherwise C# still has a delegate pointing to a function in the Lua virtual machine.
    Check this to prevent calling these invalid delegates after the virtual machine is released (They are invalid because the virtual machine on which the Lua function is referenced has been released.) from causing exceptions or even crashes.

    If you only use C# code to subscribe to events, I think it is similar to adding events in the Inspector panel, so it can be cleared when the entity is destroyed.
    It is good and harmless to unsubscribe from events that are not required. There are always strange special circumstances that trigger some events by mistake.
     
    Last edited: Dec 31, 2020
  3. Entikai

    Entikai

    Joined:
    Mar 22, 2020
    Posts:
    17
    Looking through the documentation, there is a RemoveListener() method for UnityEvents.
    Didn't know about it, but this is what I was looking for. Thanks.