Runtime(in-game) UI scripting. How can I improve this?

Hi! I’m trying to create a state machine editor for my game and I want to do it with UI Toolkit. I managed to get something on screen but I wonder if there is a better way to achieve the same thing. This is how I did it

  1. Created a box representing a state in one UXML-file. Root VisualElement named “root”

  2. Created an empty VisualElement-container in another UXML, and added it to a GameObject(named “UIContainer”) with a UIDocument. Root VisualElement named “container”.

  3. Added the box UXML to a UIDocument in a different GameObject, made a prefab and discarded the GameObject.

  4. Added this script to “UIContainer”

public class VisualScriptingManager : MonoBehaviour
{
    public Transform baseBoxPrefab;
    void Start()
    {
        var t = Instantiate(baseBoxPrefab, new Vector3(0, 0, 0), Quaternion.identity);
        var r = t.GetComponent<UIDocument>().visualTreeAsset.CloneTree();
        gameObject.GetComponent<UIDocument>().rootVisualElement.Q("container").Add(r.Q("root"));
        DestroyImmediate(t.gameObject);
    }
}

I’m sure there is a better way to do this. I’m still a Unity newbie, despite having used it on and off for years.

Bonus question: When the state box is rendered it is really small compared to what it looks like in the UI Builder. What’s that about?

Hello,

I think you can further simplify this by simply having using the VisualTreeAsset directly:

public class VisualScriptingManager : MonoBehaviour
{
    public VisualTreeAsset template;
    void Start()
    {     
        var r = visualTreeAsset.CloneTree(); // just make sure this is the root
        gameObject.GetComponent<UIDocument>().rootVisualElement.Q("container").Add(r));
    }
}

Well I’ll be damned… Thanks!

@antoine-unity Can you clue me in on the downscaling when it’s being rendered?

Can you share a bit more specifics? Screen shots, PanelSettings values, etc.

Absolutely. The PanelSettings values are the default ones (see first image). The box has a min width and abs. position, not much else. The container I’m adding to has 100% width and height.

6391398--712578--Screenshot 2020-10-07 at 09.25.01.png

The reference DPI seems a little high, try to set both dpi values at 96

That worked, although it is now slightly too big with some render artefacts. I tried changing Scale Mode to Constant Pixel Size which seems to work best.

Still, it would be interesting to know how I should handle Panel Settings, and reference DPI in particular, when it comes to different kinds of displays. Basically, I want the boxes to stay the same size as I have designed them to have, regardless of display.