简体   繁体   English

如何在Unity中的水平布局组中移动UI元素?

[英]How to move UI elements in horizontal layout group in Unity?

I have a simple parent object {Buttons Holder} that has a Horizontal Layout Group component attached to it, so when the game starts I instantiate multiple buttons in the Buttons Holder so that they line up perfectly. 我有一个简单的父对象{Buttons Holder},该对象上附加了“水平布局组”组件,因此,当游戏开始时,我在Buttons Holder中实例化了多个按钮,以便它们完美对齐。

And just for example lets say that I have 2 buttons instantiated and I want at some point these 2 buttons to switch positions so that the first button goes to the second button's position and the second button's switches to the first button's position. 举例来说,我实例化了2个按钮,并且我希望在某些时候这2个按钮切换位置,以便第一个按钮转到第二个按钮的位置,而第二个按钮切换到第一个按钮的位置。

And heres what i'm trying to do: 这就是我想要做的:

Vector3 pos1 = buttonPrefabs[0].transform.position;
Vector3 pos2 = buttonPrefabs[1].transform.position;

buttonPrefabs[0].transform.position = Vector3.Lerp(pos1, pos2, Time.deltaTime * 2);

I mean I don't want to snap them to their new positions I just want them to smoothly travel to their new positions using Vector2.lerp or something. 我的意思是我不想让他们跳到新的位置,我只是想让他们使用Vector2.lerp或其他工具平稳地移动到新的位置。

Since the parent object has a Horizontal Layout Group attached to it i'm not able to do that. 由于父对象具有附加的“水平布局组”,因此我无法做到这一点。

Help please. 请帮助。

You can not lerp them to their new position while the position is controlled by the Layout Group. 当位置由版式组控制时,您无法将其固定到新位置。 Only thing I can think of is 我唯一能想到的是

  • temporarily disable the Layout Group 暂时禁用布局组
  • then move the child objects smoothly via eg MoveTowards 然后通过例如MoveTowards平滑地移动子对象
  • update their child index values to reflect their new order accordingly 更新其子索引值以相应地反映其新顺序
  • enable the layout group again 再次启用布局组

A more sophisticated approach would require you writing your own Layout Group that offers functionality to let child objects switch positions. 一种更复杂的方法将要求您编写自己的布局组,该组具有使子对象切换位置的功能。 That way your own Layout Group could still keep all other children properly positioned, even while two children switch positions. 这样,即使两个孩子切换位置,您自己的布局组仍可以保持所有其他孩子的正确位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM