Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

(Runtime) Duplicate or Instantiate a VisualElement via code?

Discussion in 'UI Toolkit' started by BackgroundMover, Jun 22, 2020.

  1. BackgroundMover

    BackgroundMover

    Joined:
    May 9, 2015
    Posts:
    215
    I get a VisualElement via
    var myLabel = this.visualTree.Q<Label>("myLabel");

    but I can't figure out how to duplicate it and add the new instance back into the tree, as if it were a prefab. Do I have to save it to a separate UXML asset and spawn it that way whenever I want to copy something into the tree?
     
    dorianvasile and ProphetEclipse like this.
  2. ProphetEclipse

    ProphetEclipse

    Joined:
    Jun 2, 2019
    Posts:
    2
    Hey Buddy,

    I got it to work by getting the UXML of the PanelRenderer. Then getting a CloneTree() of that UXML and Query for whatever visual element I wanted cloned. Then I added it to my visualTree.

    If you want multiple clones you'd have to clone the UXML multiple times with CloneTree(). Since you can't add clonedVisual more than once.

    Code (CSharp):
    1. var cloneXML = this.uxml;
    2. VisualElement clonedVisual = cloneXML.CloneTree().Q<Label>("myLabel");
    3. this.visualTree.Add(clonedVisual);
     
    BackgroundMover likes this.
  3. uDamian

    uDamian

    Unity Technologies

    Joined:
    Dec 11, 2017
    Posts:
    1,231
    There is no way to clone VisualElements. UXML was entirely made for this purpose. Or, you can create simple C# functions that you call and they create some elements under a parent.
     
  4. conor_saber

    conor_saber

    Joined:
    Oct 14, 2022
    Posts:
    3
    You can use CTRL-D in the UI Builder to clone a VisualElement - it would be nice to have this available in C#.