tag | @param tag Имя тега для поиска GameObject 'ов. |
Возвращает список активных GameObject'ов с тегом tag
. Возвращает пустой список, если не найдено ни одного GameObject'а.
Перед использованием тег должен быть объявлен в 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 function FindClosestEnemy () : GameObject { // Find all game objects with tag Enemy var gos : GameObject[]; gos = GameObject.FindGameObjectsWithTag("Enemy"); var closest : GameObject; var distance = Mathf.Infinity; var position = transform.position; // Iterate through them and find the closest one for (var go : GameObject in gos) { var diff = (go.transform.position - position); var curDistance = diff.sqrMagnitude; if (curDistance < distance) { closest = go; distance = curDistance; } } return closest; }
// Find the name of the closest enemy 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; } }
Другой пример проверяет массив на пустоту:
// Search for game objects with a tag that is not used
function Start () { var gos : GameObject[]; gos = GameObject.FindGameObjectsWithTag("fred"); if (gos.length == 0) { Debug.Log("No game objects are tagged with fred"); } }