Version: 2017.3

GameObject.FindGameObjectsWithTag

Cambiar al Manual
public static GameObject[] FindGameObjectsWithTag (string tag);

Parámetros

tag El nombre de la tag para buscar GameObjects.

Descripción

Devuelve una lista de GameObjects activos etiquetados con tag. Devuelve un array vacío si ningún GameObject fue encontrado.

Los tags deben ser declarados en el tag manager antes de ser usados. Una UnityException será lanzada si el tag no existe, o si es ingresada como tag una cadena vacía o con valor null.

// 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); } } }

Otro ejemplo:

// 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; } }

Otro ejemplo, probar si hay un array vacío:

// 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"); } }