
在本文中3D天堂介绍了Unity的UI Toolkit的相对位置和绝对位置以及如何配置它。
简单介绍
UI Toolkit中的每个视觉元素都可以分配一个位置,可以从UI Builder的检查器中设置Relative(相对)或Absolute(绝对),如下所示。

此设置是理解UI Toolkit布局系统的重要概念。
可以从这里参阅相对和绝对定位,从这里参阅坐标和位置系统(官方文档)。
相对位置
在UI Builder中放置可视元素时,位置默认设置为相对,对于设置为Relative的Visual Elements(视觉元素),坐标由UI Toolkit的布局系统自动计算并沿一个方向对齐。
下图显示了三个视觉元素,其中Flex -Glow设置为0,高度设置为固定值,添加为子元素。

通过在Position下的Left、Top、Right、Bottom中输入值,可以根据如上所述自动计算的坐标设置相对坐标。
下面是将绿色视觉元素左侧设置为30px的示例。

在这种状态下,左上角是起点,所以即使在右边输入一个值,也不会发生变化。
可以看到,当更改父视觉元素的Flex Direction时 ,它会发生变化。
另外,将省略Flexbox的概念,例如Flex Direction的解释,因为它偏离了本文的主要观点。
绝对位置
如果Position设置为Absolute,则不会自动计算该元素的坐标,输入的坐标将相对于父可视元素。
例如,将绿色视觉元素的位置从相对更改为绝对将产生下图。

首先,可以看到绿色的Visual Element脱离了自动对齐目标,只有红色和蓝色整齐对齐,绿色元素相对于它们的父元素定位。
由于为Left输入了30px,因此可以看到它位于父级左侧30px处,如果不想像这样自动计算布局,请将Postion设置为Absolute。
在脚本中指定
要从脚本中设置上述位置设置,请执行以下操作。
Use the unity editor;
Use Unity Engine;
Use UnityEngine.UIElements;
public sealed class example: EditorWindow
{
private void CreateGUI()
{
var root = rootVisualElement;
var parent = new VisualElement();
root。add(parent);
// Red Visual Element
var red = new VisualElement();
red.style.backgroundColor = new Color( 0.75f , 0.0f , 0.0f );
red.style.width = 100.0f ;
red.style.height = 100.0f ;
red.style.position = Position.Relative;
parent.Add(red);
// Green Visual Element
var green = new VisualElement();
green.style.backgroundColor = new Color( 0.0f , 0.75f , 0.0f );
green.style.width = 100.0f ;
green.style.height = 100.0f ;
green.style.position = Position.Absolute;
green.style.left = 30.0f ;
parent.Add(Green);
// Blue Visual Element
var blue = new VisualElement();
blue.style.backgroundColor = new Color( 0.0f , 0.0f , 0.75f );
blue.style.width = 100.0f ;
blue.style.height = 100.0f ;
blue.style.position = Position.Relative;
parents。add (blue);
}
[MenuItem( "Window/Example" )]
public static void ShowWindow()
{
GetWindow<example>();
}
}
结果如下所示:

在样式表中指定
使用USS设置时,请按以下步骤操作。
#Red{
width:100px ;
high:100px;
background color:#BF0000;
position: relative;
}
#Green{
width:100px ;
high:100px;
background color:#00BF00;
position: absolute;
Left:30px;
}
#Blue{
width:100px ;
high:100 pixel;
background color:#0000BF;
position: relative;
}
…
以上是3D天堂网关于Unity中的UI Toolkit相对位置和绝对位置的全部内容,如果你有任何反馈,请随时在本页面下方留言。