Hello!
I’m making an editor using UI toolkit and I want to expand my visual element to the size of the inspector it’s being shown in, basically to make it a predictable size. Especially since it’s a large list and the list keeps changing size otherwise.
How could I go about this? I’ve tried changing a bunch of flex-grow to 1 but that did nothing. I’ve also learned that Screen.height should return the inspector height, but it doesn’t seem consistent. (It somehow changed to two different values after just selecting and deselecting? )
Any help is appreciated!
With some trickery, I’ve managed to find a solution to fill the entire inspector.
public override VisualElement CreateInspectorGUI()
{
VisualElement root = new VisualElement();
// Register a geometry changed event to update the root size to match the entire inspector.
root.RegisterCallback<GeometryChangedEvent, VisualElement>((evt, rootArgs) =>
{
// Only do this if the view port is null to save resources.
if (contentViewport == null)
{
// Find the template container.
TemplateContainer rootVisualContainer = FindParent<TemplateContainer>(rootArgs);
if (rootVisualContainer != null)
{
// Find the view port element.
contentViewport = rootVisualContainer.Q<VisualElement>("unity-content-viewport");
}
}
// The viewport exists.
if (contentViewport != null)
{
// Update the root size to match the entire inspector.
rootArgs.style.height = contentViewport.resolvedStyle.height - 70;
}
}, root);
return root;
}
private static T FindParent<T>(VisualElement element, string name = null) where T : VisualElement
{
VisualElement parent = element;
do
{
parent = parent.parent;
if (parent != null && parent.GetType() == typeof(T))
{
if (!string.IsNullOrEmpty(name) && parent.name != name)
{
continue;
}
return (T) parent;
}
} while (parent != null);
return null;
}
I mean with the right style settings it should be automatically expanding.
Otherwise there’s a built in extension method for this: Unity - Scripting API: UIElements.VisualElementExtensions.StretchToParentSize