从指定节点开始遍历该节点下的所有子节点,并保存到list中
List<GameObject> GetChildObjects(GameObject parent)
{
List<GameObject> childList = new List<GameObject>();
for (int i = 0; i < parent.transform.childCount; i++)
{
childList.Add(parent.transform.GetChild(i).gameObject);
if (parent.transform.GetChild(i).childCount > 0)
{
childList.AddRange(GetChildObjects(parent.transform.GetChild(i).gameObject));
}
}
return childList;
}
通过一个点坐标,获取最靠近的那个对象
GameObject GetNearestObject(Vector3 point)
{
GameObject nearestObject = null;
float nearestDistance = Mathf.Infinity;
foreach(GameObject obj in allObjects)
{
float distance = Vector3.Distance(obj.transform.position, point);
if(distance < nearestDistance)
{
nearestDistance = distance;
nearestObject = obj;
}
}
return nearestObject;
}
其中,allObjects是指场景中的所有对象的列表。