Search Unity

Unload/Replace uxml file to show different ui-builder generated file

Discussion in 'UI Toolkit' started by jGate99, Nov 4, 2019.

  1. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,945
    Hi there,

    So i created a login form and a list view (2 seperate files) with ui builder.
    Now im able to show first file using this approach

    Now assuming, user press the button and i get event in callback, how do i unload current file and switch to 2nd file with its own uss etc.

    Please advise

    Capture.PNG
     
  2. uDamian

    uDamian

    Unity Technologies

    Joined:
    Dec 11, 2017
    Posts:
    1,231
    First off, if you created the uxml file with the UI Builder, you don't need to explicitly load the .uss file in C# and assign it via `root.styleSheets.Add()`. This should happen automatically.

    As for switching "files", it doesn't quite work like that. You `uxml` variable above stores a reference to a VisualTreeAsset (the asset type created from a .uxml file). You can then instantiate this asset as VisualElements via the CloneTree(root) call, as you do. You can do this multiple times and you can also do this inside any other VisualElement, not just root.

    With that in mind, to "switch" files, one option is to just load both uxml files via the AssetDatabase (let's call them uxml1 and uxml2). You can then:
    1. Clone uxml1 into the root and when the user sends your event call `root.Clear()` and re-clone uxml2 into the root, OR
    2. Clone both uxml1 and uxml2 using the no-arguments CloneTree() call (this will create a container element for you), then Add() uxml1Cloned to the root. When the user sends the event, call uxml1Cloned.RemoveFromHierarchy() and Add() uxml2Cloned to the root - keeping around uxml1Cloned for later use
    3. Clone both as in 2. but instead of Add()/Remove() you just Add() both right away and simply change the .style.display uss property between visible/hidden on the section you want currently shown (this is the most efficient option)
     
    jGate99 likes this.
  3. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,945
    Thank you for your detailed reply. Now i understand fully how to show different views on different inputs and with different strategies.

    In my case, 1-2 will work as login will only appear once and wont appear again.
     
    uDamian likes this.