c# - 如何从 foreach gameobject.transform 获取最后几个元素

标签 c# unity3d foreach

目前我通过使用 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 个元素

最佳答案

您可以使用 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,子项在其后)。一个更确定和更简单的方法是你的游戏对象的每个 child 都有一个特定的组件,比方说:

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

您可以在每个 child 中设置 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() 函数中存储子数组,然后再使用它的问题。

关于c# - 如何从 foreach gameobject.transform 获取最后几个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34714150/

相关文章:

c# - 当 Key 被 Player Unity 2d 捕获时进入下一关

c# - 缺少方法 UnityEngine.VR.VRSettings.get_enabled |未处理 Unity IAP 购买 |安卓

ios - 地形光照问题 Unity

c# - 列表框中的 Foreach 语句

JavaScript:在 'break' 循环内模拟 'foreach'

c# - 将 sbyte[] 转换为 bool[] 并将 char[] 转换为 short[]

c# - 如何记录存储过程错误

c# - 在 Assert.Multiple 中验证模拟

c# - C# 中动态对象的赋值是如何工作的?

ios - JSON 处理错误 : Output not fetched correctly