Search Unity

Registered Callbacks Stop Working After Document is Reactivated

Discussion in 'UI Toolkit' started by bugbeeb, Mar 20, 2022.

  1. bugbeeb

    bugbeeb

    Joined:
    Oct 19, 2021
    Posts:
    22
    I created a fresh scene and added a UI document with a script. The script has Start, OnEnable, OnDisable. In Start I register a mousedown event and in OnEnable/OnDisable I register/unregister a mouseover event like
    ```
    doc.rootVisualElement.RegisterCallback<MouseDownEvent>(e => Debug.Log("Down"));
    ```
    These all work fine when the game starts up. After I disable either the doc or the parent game object and re-enable it, no events fire.
    Unity v2022.1.0b9
     
    Last edited: Mar 21, 2022
  2. JuliaP_Unity

    JuliaP_Unity

    Unity Technologies

    Joined:
    Mar 26, 2020
    Posts:
    700
    You should use OnEnable to get the reference to the root visual element of a UIDocument, as it's recreated every time its own OnEnable runs, so it stops working for you because the whole UI got recreated when you disabled/re-enabled the game object.

    However, you should reconsider disabling/re-enabling game objects if possible, as with UI Toolkit it's possible to make the UI "disappear" by setting the
    style.display
    to
    DisplayStyle.None
    to make it go away, and then back to
    DisplayStyle.Flex
    to bring it back. That way you don't re-create the UI each time.

    Hope this helps! :)
     
    TheWanderingBen likes this.
  3. bugbeeb

    bugbeeb

    Joined:
    Oct 19, 2021
    Posts:
    22
    @JuliaP_Unity Thanks for your response. That does indeed fix my issue as I didn't realize the element tree was being recreated each time
     
    JuliaP_Unity likes this.
  4. TheWanderingBen

    TheWanderingBen

    Joined:
    Nov 3, 2015
    Posts:
    98
    Wow, struggled for a few hours with this, did not realize that was my problem. Thanks for the thread all!
     
    JuliaP_Unity likes this.
  5. Predulus

    Predulus

    Joined:
    Feb 5, 2018
    Posts:
    90
    Does this also affect event callbacks?
     
    Propagant likes this.
  6. Propagant

    Propagant

    Joined:
    Nov 18, 2013
    Posts:
    38
    Same question here... Should I unsubscribe from the events or are they handled automatically somehow?