如何从foreach gameobject.transform中获取最后几个元素

本文关键字:元素 几个 最后 获取 foreach gameobject transform | 更新日期: 2023-09-27 18:29:41

当前我通过使用if语句检查数组的每个循环来手动执行此操作

float addGap = gapFix;
foreach (Transform child in topViewPlan.transform)
{
    if (child.name.Substring(5, 2).Equals("45") || child.name.Substring(5, 2).Equals("46") || child.name.Substring(5, 2).Equals("47") || child.name.Substring(5, 2).Equals("48"))
    {
        //rearrange child position
        if (!child.name.Substring(5, 2).Equals("45"))
            child.transform.localPosition += Vector3.right * addGap * 2;
        else
            child.transform.localPosition += Vector3.right * addGap;
    }
}

有没有可能得到topViewPlan.transform的最后几个元素?举个例子,假设topViewPlan.transform由10个元素组成,我想要最后4个元素(即元素7,8,9和10),所以也许我可以写:-

foreach (Transform child in topViewPlan.transform.getLast(4)){} //this is just example

所以我可以得到topViewPlan.transform 的最后4个元素

如何从foreach gameobject.transform中获取最后几个元素

您可以使用GetComponentsInChildren<Transform>(),它将为您和数组提供子对象和对象本身。

例如:

var childs = GetComponentsInChildren<Transform>();
int offset = 5; // want the five last elements
for(int i=childs.Length - offset; i<childs.Length; ++i)
{
    // Do something with childs[i]
}

但我认为这段代码效率低下且不稳定,我无法确保GetComponentsInChildren返回的数组以正确的方式排序(父级为0,子级为0)。一个更确定和简单的方法是,你的游戏对象的每个孩子都有一个特定的组件,比如说:

class ChildrenIdentificator : MonoBehavior
{
    public int id = 0;
}

你可以在每个孩子身上设置id,这样它就有了你想要的行为,然后你就可以这样做了:

var childs = GetComponentsInChildren<ChildrenIdentificator>();
for(int i=0 ; i<childs.Length ; ++i)
{
    if(childs[i].id == // I let you figure out the rest
}

这样你就可以更好地控制自己,你可以直接看到自己在做什么。您还可以避免进行字符串比较。在任何情况下,我强烈建议不要在每帧使用GetComponentsInChildren,以解决您可以在以后使用子数组之前将其存储在Start()函数中的问题。

使用

transform.childCount

要获得孩子的数量,然后要获得一个孩子,请执行以下操作:

例如,这将返回子编号5:

transform.GetChild(5);

你需要的代码:

int numberOfChildNeeded = 5;
for (int i = transform.childCount - 1; i > transform.childCount - numberOfChildNeeded ; i--)
{
    //do something
    transform.GetChild(i)
}