- Home /
how to add visual elements at runtime using unity's new UI Toolkit/UI Builder
I want to add as many visual elements or buttons using UI toolkit, as I have nodes or skills in my tech tree, problem I am facing is how do I add onto the UXML file or the style sheet at runtime . any help will be appreciated.
Answer by andrew-lukasik · Mar 31 at 09:55 PM
Start with this:
TestUiController.cs
public class TestUiController : MonoBehaviour
{
[SerializeField] UIDocument _UIDocument = null;
void OnEnable ()
{
var ROOT = _UIDocument.rootVisualElement;
var label1 = new Label( "Hell-o-world" );
ROOT.Add( label1 );
var button1 = new Button( () => {
Debug.Log("Button clicked, mission accomplished! :T");
} );
button1.AddToClassList( "uss class name for more specific style" );
ROOT.Add( button1 );
}
}
thankssss a ton mate, was stuck for too long on this. one quick little follow up.this adds a button in the root of the visual tree asset or uxml file right, but if i were to add a button into a specific visual element in the root , how would i go about doing that? also is it possible to add a button uxml prefab into the document? thanks again
to add a button into a specific visual element
// note: element names are displayed in ui Builder with a "#" prefix
var specificElement = ROOT.Q<VisualElement>( "element-name" );
if( specificElement!=null )
{
specificElement.Add( new Label("found it!") );
}
else Debug.Log( "element not found" );
is it possible to add a button uxml prefab into the document?
// make sure this file exists: (...)/Resources/UI/myButton.uxml
var myButtonUxml = Resources.Load<VisualTreeAsset>("UI/myButton");
var myButtonIntance = myButtonUxml.CloneTree();
ROOT.Add( myButtonIntance);