前言
在开发中,会遇到某种列表的元素需要顺序调整的功能,在查看完transform节点的操作发现用自带的内置函数可以直接实现上述功能的UI节点切换,至于数据需要自己进行替换。
效果
接口函数
//
// 摘要:
// Move the transform to the start of the local transform list.
public void SetAsFirstSibling();
//
// 摘要:
// Move the transform to the end of the local transform list.
public void SetAsLastSibling();
//
// 摘要:
// Sets the sibling index.
//
// 参数:
// index:
// Index to set.
public void SetSiblingIndex(int index);
如上函数:
SetAsFirstSibling是快速置顶,等同于SetSiblingIndex(0)。
SetAsLastSibling是快速置底,等同于SetSiblingIndex(兄弟节点数 - 1)。
SetSiblingIndex 直接设置节点的下标。
功能实现
功能实现就是UI配合如上的三个接口,实现上移、下移、置顶、置底等功能。
UI搭建
UI的搭建如图:
主要是一个列表中有几个节点,每个节点有几个操作按钮,上移下移等。
编码实现
直接上代码:
using UnityEngine;
public class SiblingTest : MonoBehaviour
{
public void ClickTop(GameObject obj) {
obj.transform.SetAsFirstSibling();
}
public void ClickBottom(GameObject obj)
{
obj.transform.SetAsLastSibling();
}
public void ClickMoveUp(GameObject obj)
{
int idx = obj.transform.GetSiblingIndex();
if (idx > 0)
obj.transform.SetSiblingIndex(idx - 1);
}
public void ClickMoveDown(GameObject obj)
{
int idx = obj.transform.GetSiblingIndex();
int count = obj.transform.parent.childCount;
if(idx < count -1)
obj.transform.SetSiblingIndex(idx + 1);
}
}
上移时,下标 -1,
下移时,下标 +1,
只不过下标操作的时候判断一下数值范围,防止下标越界。
置顶和置底直接调用接口。