Вы можете искать каждый объект в сцене с помощью Transform
, затем искать искать объекты с позициями x и z и возвращать тег. Функции Resources.FindObjectsOfTypeAll
и GameObject.FindObjectsOfType
могут сделать это, но для повышения производительности используйте Scene.GetRootGameObjects
, чтобы получить все корневые объекты и цикл через дочерние элементы от каждого корневого объекта с помощью GetComponentsInChildren<Transform>
и проверить, если x и z позиция соответствует.
Используйте их, потому что они не возвращают массив, а просто заполняют список.
Поиск всех объектов на сцене :
private List<GameObject> rootGameObjects = new List<GameObject>();
private List<Transform> childObjs = new List<Transform>();
private void GetAllRootObject()
{
Scene activeScene = SceneManager.GetActiveScene();
activeScene.GetRootGameObjects(rootGameObjects);
}
private void GetAllChildObjs()
{
for (int i = 0; i < rootGameObjects.Count; ++i)
{
GameObject obj = rootGameObjects[i];
//Get all child components attached to this GameObject
obj.GetComponentsInChildren<Transform>(true, childObjs);
}
}
Поиск тега объекта с позицией x, z :
bool xzEquals(Vector3 pos1, Vector3 pos2)
{
return (Mathf.Approximately(pos1.x, pos2.x)
&& Mathf.Approximately(pos1.z, pos2.z));
}
string GetTagFromPos(float x, float z)
{
Vector3 pos = new Vector3(x, 0, z);
rootGameObjects.Clear();
childObjs.Clear();
GetAllRootObject();
GetAllChildObjs();
//Loop through all Objects
for (int i = 0; i < childObjs.Count; i++)
//check if x and z matches then return tag
if (xzEquals(childObjs[i].position, pos))
return childObjs[i].tag;
return null;
}
GameObject GetObjectFromPos(float x, float z)
{
Vector3 pos = new Vector3(x, 0, z);
rootGameObjects.Clear();
childObjs.Clear();
GetAllRootObject();
GetAllChildObjs();
//Loop through all Objects
for (int i = 0; i < childObjs.Count; i++)
//check if x and z matches then return the Object
if (xzEquals(childObjs[i].position, pos))
return childObjs[i].gameObject;
return null;
}
* 1021 ИСПОЛЬЗОВАНИЕ *:
//Get tag from x, z pos
Debug.Log(GetTagFromPos(1, 2));
//Get object from x, z pos
Debug.Log(GetObjectFromPos(1, 2));
Вы также можете вручную поместить Объекты, которые хотите найти, в Список, если хотите сэкономить время в цикле.