C# 如何从foreach gameobject.transform中获取最后几个元素
目前,我通过使用C# 如何从foreach gameobject.transform中获取最后几个元素,c#,unity3d,foreach,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.n
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(),它将为您提供和数组以及子对象和对象本身
例如:
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]
}
您可以在每个孩子中设置id,使其具有您想要的行为,然后您可以执行以下操作:
var childs = GetComponentsInChildren<ChildrenIdentificator>();
for(int i=0 ; i<childs.Length ; ++i)
{
if(childs[i].id == // I let you figure out the rest
}
var childs=GetComponentsInChildren();
对于(int i=0;i使用
要获取孩子数,然后要获取孩子数,请执行以下操作:
例如,这将返回子编号5:
transform.GetChild(5);
您需要的代码:
int numberOfChildNeeded = 5;
for (int i = transform.childCount - 1; i > transform.childCount - numberOfChildNeeded ; i--)
{
//do something
transform.GetChild(i)
}
如果需要获取停用的对象,请将true参数添加到GetComponentsInChildren。我更喜欢第一种方法,但问题是var childs=GetComponentsInChildren();
递归地返回子对象,而foreach(在topViewPlan.Transform中转换子对象)
只返回子对象的第一个深度。
transform.GetChild(5);
int numberOfChildNeeded = 5;
for (int i = transform.childCount - 1; i > transform.childCount - numberOfChildNeeded ; i--)
{
//do something
transform.GetChild(i)
}