Search Unity

Why no "UNregisterCallback" in Royale Runtime Demo

Discussion in 'UI Toolkit' started by qwert024, Jan 13, 2022.

  1. qwert024

    qwert024

    Joined:
    Oct 21, 2015
    Posts:
    43
    Hi,
    I was trying to learn UI Toolkit with UI Toolkit Unity Royale Runtime Demo
    I saw something like this: someButton.RegisterCallback<SomeEvent>(ev => DoSomething());
    but I didn't saw it unregister the callback somewhere
    However to my understanding usually we should unregister our callbacks.
    I was wondering if I misunderstand something?
    It would be awesome if someone could help explain!

    some codes from the demo project:
    Code (CSharp):
    1.  
    2. void OnEnable()
    3.         {
    4.             // Retrieving interesting elements to:
    5.             // 1- set values
    6.             // 2- assign behaviors
    7.             // 3- animate!
    8.             var rootVisualElement = GetComponent<UIDocument>().rootVisualElement;
    9.  
    10.             matchOverLabel = rootVisualElement.Q<Label>("match-over-label");
    11.  
    12.             winnerIsLabel = rootVisualElement.Q<Label>("winner-is-label");
    13.  
    14.             winnerTeamNameLabel = rootVisualElement.Q<Label>("winner-label");
    15.  
    16.             mainMenuButton = rootVisualElement.Q<Button>("main-menu-button");
    17.  
    18.             // Attaching callback to the button.
    19.             mainMenuButton.RegisterCallback<ClickEvent>(ev => OnMainMenuButton());
    20.         }
     
  2. manuelgoellnitz

    manuelgoellnitz

    Joined:
    Feb 15, 2017
    Posts:
    397
    Hm and it gets worse...
    Since the Register is in OnEnable(), deactivating and reactivating the compoment would register the callback again, aka OnMainMenuButton() would be called multiple times.
     
  3. JuliaP_Unity

    JuliaP_Unity

    Unity Technologies

    Joined:
    Mar 26, 2020
    Posts:
    700
    This doesn't happen, because the hierarchy is reconstructed on
    OnEnable
    so the callback is registered to the newly created UI elements.

    If you want you can unregister callbacks on
    OnDisable
    , for example. This example hasn't been updated in a while and is not perfect for sure! But it's not a huge deal if you don't unregister in this situation, which is why it wasn't done initially.
     
  4. qwert024

    qwert024

    Joined:
    Oct 21, 2015
    Posts:
    43
    Got it. Thanks for clarification!