Starting from the specified node, traverse all child nodes under the node and save them to the 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;
}
Get the closest object through a point coordinate
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;
}
Among them, allObjects refers to the list of all objects in the scene.