Unity starts from the specified node and traverses all child nodes under the node and saves them to the list.

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.

2e200195f97b1624c978cef41e0b72fe.jpeg

Guess you like

Origin blog.csdn.net/shguxudong11/article/details/129441832
Recommended