问题描述
我有一个父模型,它有大约50个gameObjects作为子模型。我正在编写一个脚本,以在远离父级但靠近父级的随机位置缓慢移动子级gameObjects。这样看起来就像网格正在缓慢分裂。
由于少数网格的顺序为parent->children->subchildren
,因此我必须将此脚本附加到其每个子级。我使用foreach (Transform child in parent.transform)
时找不到子孩子。如何实现它,以便可以将脚本添加到父级,所有子级都会对其起作用?
public float speed = 2.0f;
public float Position_x;
public float Position_z;
public Vector3 FinalPos;
void Start()
{
Position_x = Random.Range(-1.5f,3f);
Position_z = Random.Range(-1.5f,3f);
FinalPos= new Vector3(Position_x,transform.position.y,Position_z);
}
void Update()
{
transform.position = Vector3.Lerp(transform.position,FinalPos,Time.deltaTime * speed)
}
解决方法
您可以使用foreach (Transform child in transform)
而不是foreach (Transform child in parent.transform)
来实现它,因为我们使用transform.parent
来访问父对象的变换,而不使用parent.transfom
和transform
来进行对象的变换。
因为 transform 是存储对象,父级和子级转换以及许多其他内容的对象,所以您可以:
public List<GameObject> Children; // you can store that children objects if you intend to use them later.
foreach (Transform child in transform)
{
if (child.tag == "Tag")// also if you need to specify a specific child using Tags
{
Children.Add(child.gameObject);// to add the object in that List
//your operations or movement...
}
}
别忘了将此脚本分配给父对象。
编辑
您还可以使用transform.GetChild(index)
获取特定子项的变换,其中索引是子项变换的数量(该索引是从零开始的数字)