The style of dynamically created Element is broken

I created a VisualTreeAsset and set the USS in UI Builder. If you set it as a UIDocument and run it, the style will look as intended, as defined in UI Builder.

However, if you use that USS to dynamically create a UI Element, the appearance will always be corrupted. (It seems that the style defined by Unity’s default is used.)

Strangely, it seems that some things get corrupted and some don’t.

For example, buttons and input fields always get corrupted, but Foldout doesn’t seem to be the same.

Here’s what I tried.

  • If you write a style (such as text color) directly to something that is dynamically generated, it will be reflected.
  • Even if you attach style sheets one by one to something that is dynamically generated, the style will not be reflected.

And this is the script that dynamically generates it.

_root = new VisualElement();
_root.styleSheets.Add(styleSheet);
uiDocument.rootVisualElement.Add(_root);

_root.Add(new new IntegerField());