Search Unity

Question How do I get a child component to show up?

Discussion in 'UI Toolkit' started by Snackmix, May 29, 2023.

  1. Snackmix

    Snackmix

    Joined:
    Apr 3, 2013
    Posts:
    36
    I've been toying around trying to learn UI Toolkit. I wanted to break my UI elements into smaller components like you would when developing for the web i.e. React/Angular.

    So I decided to make a small health bar component, and then tried to load it into another component as a template. When I do this the health bar does not show up. It looks like the width/height are not applied correctly, and if I do change the width and height manually in the UI Builder, the whole health bar is still not visible.

    I had each of these in separate folders with their own .cs, .uxml, .uss files so that I could keep things neatly organized.

    What is the correct way to create a UI component, and how do I get it to show up in a different UI asset?
     

    Attached Files:

  2. cpalma-unity

    cpalma-unity

    Unity Technologies

    Joined:
    Nov 30, 2020
    Posts:
    110
    Hello! I think you are going in the right direction. From what I can see in the debugger your script is not instantiating the uxml file. There should be some code like this in the constructor of your control:

    Code (CSharp):
    1. var asset = Resources.Load<VisualTreeAsset>("PlayerHealthBar");
    2. asset.CloneTree(this);
    Here is the full example of how to work with uxml files and C# files:
    https://docs.unity3d.com/Manual/UIE-encapsulate-uxml-with-logic.html
     
  3. Snackmix

    Snackmix

    Joined:
    Apr 3, 2013
    Posts:
    36
    Thank you so much! I had been digging through the docs but had not stumbled across this, it seems like exactly what I need.

    I'm going to give this a shot once I get home tonight.
     
  4. Snackmix

    Snackmix

    Joined:
    Apr 3, 2013
    Posts:
    36
    Alright it seems like my issue was that I had drug the C# file to the PlayerSummary document, and the uxml like I had meant to. This actually fixed it and now the health bar now renders. Thanks!
     
    cpalma-unity likes this.