I want to place a button in the lower right corner of the window, and its position relative to the lower right corner shall not change with the size of the window. For instance:
The “next” button at the lower right. However, no matter how I set its parameters, it seems not responsive at all.
I’ve tried to set the position to absolute, and set bottom and right to a fixed value, and adjusting the margin, but none of them worked. Can anyone help me?
Actually I just figured out that the reason of my previous code’s not working, which is because of the C# code behind.
When you create a new editor window using UI Builder, some snippets will be generated automatically. However, they are not really “proper”. The code is like:
public class DemoWindow : EditorWindow
{
[MenuItem("Window/UI Toolkit/DemoWindow")]
public static void ShowExample()
{
DemoWindow wnd = GetWindow<DemoWindow>();
wnd.titleContent = new GUIContent("DemoWindow");
}
public void CreateGUI()
{
// Each editor window contains a root VisualElement object
VisualElement root = rootVisualElement;
// VisualElements objects can contain other VisualElement following a tree hierarchy.
VisualElement label = new Label("Hello World! From C#");
root.Add(label);
// Import UXML
var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Scripts/CustomWindows/DemoWindow.uxml");
VisualElement labelFromUXML = visualTree.Instantiate();
root.Add(labelFromUXML);
}
}
The thing is, the visual tree will be added to the root, or say, being a child of it, and then, there will be a root visual element whose size is auto. (This is just my personal understanding, it may not be right).
To fix this problem, instead of instantiate a new visual element and add it to the root, actually we can clone the visual tree to the root, and then there will be no more additional parent visual element.
var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Scripts/CustomWindows/DemoWindow.uxml");
visualTree.CloneTree(rootVisualElement);
Yes! There is a difference between using Instantiate + Add and CloneTree. The first one will keep a root element (TemplateContainer) for the instantiated template and the second one will just instantiate the content of your template and add it directly to the provided root.
Having a TemplateContainer might be useful in some cases since its C# class has some functions to know the source of the original template. When you use CloneTree you lose this extra information but you don’t have the extra root element