Search Unity

Resolved UIDocuments working unreliably + workaround

Discussion in 'UI Toolkit' started by andrew-lukasik, Sep 16, 2020.

  1. andrew-lukasik

    andrew-lukasik

    Joined:
    Jan 31, 2013
    Posts:
    249
    Solved: to register UIDocument events use OnEnable().


    While moving my scripts from PanelRenderer + postUxmlReload api to UIDocument I discovered that mu UI isn't working well anymore. I register my events for Buttons and Sliders in Start() methods, as seen elsewhere in github repo, but they weren't working reliably (only one of UIDocument worked... for no clear reason too).
    Strongly suspecting a race condition here I created a simple script:
    Code (CSharp):
    1. void Awake ()
    2. {
    3.     // workaround for UIDocument binding not working, part 1/2
    4.     var arr = FindObjectsOfType<UIDocument>();
    5.     foreach( var comp in arr )
    6.         comp.gameObject.SetActive(false);
    7. }
    8.  
    9. void Start ()
    10. {
    11.     // workaround for UIDocument binding not working, part 2/2
    12.     var arr = FindObjectsOfType<UIDocument>( includeInactive:true );
    13.     foreach( var comp in arr )
    14.         comp.gameObject.SetActive(true);
    15. }
    and to my surprise - it solved the issue!
    But... why?


    Unity 2020.1.5f1, UI Toolking 1.0.0-preview.8
     
    Last edited: Sep 16, 2020
  2. JuliaP_Unity

    JuliaP_Unity

    Unity Technologies

    Joined:
    Mar 26, 2020
    Posts:
    698
    Hello, I'm not sure what examples you're referring to on github repo but the best practice we suggest to follow is to register your events on OnEnable, and not on Start, as the UIDocument component initializes its rootVisualElement on OnEnable only. Possibly what you did is causing OnEnable to run at that point, which is why then it works.

    Can you move your registering of events to your OnEnable, remove this workaround and let us know how it goes? :)
     
  3. andrew-lukasik

    andrew-lukasik

    Joined:
    Jan 31, 2013
    Posts:
    249
  4. JuliaP_Unity

    JuliaP_Unity

    Unity Technologies

    Joined:
    Mar 26, 2020
    Posts:
    698
  5. andrew-lukasik

    andrew-lukasik

    Joined:
    Jan 31, 2013
    Posts:
    249
    I removed workaround, moved event registration to OnEnable and it works even better than before :)
    Thank you @JuliaP_Unity !
     
    Last edited: Sep 16, 2020
    JuliaP_Unity likes this.