[英]How to add first child to an Array-List
I'm trying to make an array or a list with the first childs of a GameObject so I can edit them from another scripts. 我正在尝试使用GameObject的第一个子项创建数组或列表,以便我可以从其他脚本编辑它们。
I have tried it doing an Array, but it will take the childs of this childs too and I need to take only the first ones. 我已经尝试过做一个数组,但它也需要这个孩子的孩子,我只需要拿第一个。
I have tried also with a List with a foreach, but it will add the same element every frame to the list, and I only need it one time. 我也尝试使用带有foreach的List,但它会在列表中每帧添加相同的元素,而我只需要一次。
public GameObject GOGranjaTerrain;
public GameObject GOFabricaTerrain;
public GameObject GOOficinaTerrain;
public Transform[] granjaTerrainArray;
public Transform[] fabricaTerrainArray;
public Transform[] oficinaTerrainArray;
public List<Transform> granjaTerrainList = new List<Transform>();
void Update()
{
SearchTerrains1();
SearchTerrains2();
}
//Array way
void SearchTerrains1()
{
granjaTerrainArray = GOGranjaTerrain.GetComponentsInChildren<Transform>();
fabricaTerrainArray = GOFabricaTerrain.GetComponentsInChildren<Transform>();
oficinaTerrainArray = GOOficinaTerrain.GetComponentsInChildren<Transform>();
}
//List way
void SearchTerrains2()
{
foreach(Transform child in GOGranjaTerrain.transform)
{
granjaTerrainList.Add(child);
}
}
Here's how you can do it: 这是你如何做到的:
void Update()
{
for (int i = 0; i < GOGranjaTerrain.transform.childCount; i++)
{
Transform child = GOGranjaTerrain.transform.GetChild(i);
if (granjaTerrainList.Contains(child) == false)
{
granjaTerrainList.Add(child);
}
}
}
Or even better, if you only need to do it once - do in in Start instead of Update. 或者甚至更好,如果你只需要做一次 - 在开始而不是更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.