GameObject.FindGameObjectsWithTag

Switch to Manual
public static GameObject[] FindGameObjectsWithTag (string tag);

Parameters

tag@param tag Имя тега для поиска GameObject'ов.

Description

Returns an array of active GameObjects tagged tag. Returns empty array if no GameObject was found.

Перед использованием тег должен быть объявлен в tag manager. Если тег не существует или задана пустая строка или null передан как тег, то будет брошено исключение UnityException.

// Instantiates respawnPrefab at the location
// of all game objects tagged "Respawn".

using UnityEngine; using System.Collections;

public class ExampleClass : MonoBehaviour { public GameObject respawnPrefab; public GameObject[] respawns; void Start() { if (respawns == null) respawns = GameObject.FindGameObjectsWithTag("Respawn");

foreach (GameObject respawn in respawns) { Instantiate(respawnPrefab, respawn.transform.position, respawn.transform.rotation); } } }

Другой пример:

// Find the name of the closest enemy

using UnityEngine; using System.Collections;

public class ExampleClass : MonoBehaviour { public GameObject FindClosestEnemy() { GameObject[] gos; gos = GameObject.FindGameObjectsWithTag("Enemy"); GameObject closest = null; float distance = Mathf.Infinity; Vector3 position = transform.position; foreach (GameObject go in gos) { Vector3 diff = go.transform.position - position; float curDistance = diff.sqrMagnitude; if (curDistance < distance) { closest = go; distance = curDistance; } } return closest; } }

Другой пример проверяет массив на пустоту:

using UnityEngine;

// Search for game objects with a tag that is not used

public class Example : MonoBehaviour { void Start() { GameObject[] gameObjects; gameObjects = GameObject.FindGameObjectsWithTag("Enemy");

if (gameObjects.Length == 0) { Debug.Log("No game objects are tagged with 'Enemy'"); } } }
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961