Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to update elements prior to setting gameobject active?

Discussion in 'UI Toolkit' started by unitydungeonmas, Sep 9, 2020.

  1. unitydungeonmas

    unitydungeonmas

    Joined:
    Sep 6, 2020
    Posts:
    37
    i have some code like this, while the current "gameObject" is not active, and it throws an error:

    Code (CSharp):
    1. VisualElement root = gameObject.GetComponent<UIDocument>().rootVisualElement;
    2.  
    3. VisualElement label = root.Q<Label>("label");
    4. label.text = "New label";
    and this is fixed by

    Code (CSharp):
    1.  
    2. gameObject.setActive(true);
    3. VisualElement root = gameObject.GetComponent<UIDocument>().rootVisualElement;
    4.  
    5. VisualElement label = root.Q<Label>("label");
    6. label.text = "New label";
    but i want to set elements before making the gameObject active, is there a way to do this?
     
  2. unitydungeonmas

    unitydungeonmas

    Joined:
    Sep 6, 2020
    Posts:
    37
    bump? how do people prefill data for an UI VisualElement before putting it on screen?
     
  3. JuliaP_Unity

    JuliaP_Unity

    Unity Technologies

    Joined:
    Mar 26, 2020
    Posts:
    696
    The behavior you're seeing is expected for UIDocuments because the rootVisualElement isn't created until OnEnable runs. If you put your code on the OnEnable of the companion MonoBehaviour you made, it'll run after the UIDocument's OnEnable and then you'll set the values as it's becoming enabled - would that work for you?

    By doing so, you also guarantee that Live Reloading your UI will work without issues, as the whole UI gets recreated on UXML/USS file changes, so you'll want your own code to run as well.

    Hope this helps! :D
     
  4. unitydungeonmas

    unitydungeonmas

    Joined:
    Sep 6, 2020
    Posts:
    37
    thanks! definitely want to learn the good practice patterns, this makes sense to me!
     
    JuliaP_Unity likes this.