How to order the childs of a parent programmatically correctly

Hi there! I am programmatically creating a visual element tree and having problems ordering the elements after they have been created.

First, let me explain the problem properly:

I have the following visual element tree:

-Element A (parent)

  • Element B (child)
  • Element C (child)
  • Element D (child)

Then, after a while, we need to update the visual tree, adding a new child and reordering it to the following:

-Element A (parent)

  • Element C (child)
  • Element B (child)
  • Element F (child)
  • Element D (child)

The only information that I have to order the list is which element is right from the other. Example:

-Element A (parent)

  • Element C (child)
  • Element B (child) (right of Element C)
  • Element F (child) (right of Element B)
  • Element D (child) (right of Element D)

This can happen a lot so performance is important, I want to reorder the elements instead of recreating them.

I have noticed that I have the following functions:

public void Sort(Comparison<VisualElement> comp)
public void BringToFront()
public void SendToBack()
public void PlaceBehind(VisualElement sibling)
public void PlaceInFront(VisualElement sibling)

However, when I use the PlaceInFront , only the two last elements are ordered correctly.

Code:

         leftVisualElement.PlaceInFront(nextVisualElement);

I have tried also the Sort function but nothing happens. It doesn’t seem to be called

Any idea on how to accomplish this?

using Windows and Unity 2020.3.34f1

Since this is for 2020.3, I assume this is using the UI Toolkit package, correct?

You may have to call PlaceInFront multiple times (once per child) to make sure the full order is exactly what you want.

When you say nothing happens with Sort, do you mean the callback is never called?