Search Unity

Question Instantiating visual elements from C#

Discussion in 'UI Toolkit' started by Maverick, Sep 2, 2020.

  1. Maverick

    Maverick

    Joined:
    Dec 18, 2009
    Posts:
    240
    1. From docs and forum following is recommended:
    Code (CSharp):
    1.  
    2. VisualTreeAsset uiAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("myUXML.uxml");
    3. VisualElement ui = uiAsset.Instantiate(); // or CloneTree()
    4.  
    5. someRootVisualElement.Add(ui);
    6.  
    Now, this code works fine, but with some inconveniences. It adds a TemplateContiner and thus encapsulates any styles defined in asset UXML. I'll have to manually add styles to TemplateContiner to suit my needs.

    Now question is, is it ok to do following, or am I instantiating visual elements in a wrong way?
    Code (CSharp):
    1.  
    2. VisualTreeAsset uiAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("myUXML.uxml");
    3. VisualElement ui = uiAsset.Instantiate().Q<MyVisualElement>();
    4.  
    5. someRootVisualElement.Add(ui);
    6.  
    That way defined style works without any additional work.


    PS: Is there a way to debug runtime, or still planned?
     
  2. jonathanma_unity

    jonathanma_unity

    Unity Technologies

    Joined:
    Jan 7, 2019
    Posts:
    229
    Hi Maverick,

    I suggest that you pass your container element when calling CloneTree();

    Code (CSharp):
    1. VisualTreeAsset uiAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("myUXML.uxml");
    2.  
    3. uiAsset.CloneTree(someRootVisualElement);
    This way the VisualTreeAsset tree will get added directly into someRootVisualElement.
     
  3. Maverick

    Maverick

    Joined:
    Dec 18, 2009
    Posts:
    240
    Thanks!

    PS: Is there a way to debug runtime ui, or still planned?
     
  4. JuliaP_Unity

    JuliaP_Unity

    Unity Technologies

    Joined:
    Mar 26, 2020
    Posts:
    700
    Have you tried the UI Toolkit Debugger? Just click the menu for any view (like the Game View) and select it there, you then find your Panel Settings on the list of panels (upper left).

    If that's not what you meant, please let us know what it is that you're looking for :)
     
  5. Maverick

    Maverick

    Joined:
    Dec 18, 2009
    Posts:
    240
    Yes, I tried UI Toolkit Debugger. Just didn't check Panel Settings.

    Thanks for hint.