Version: 2022.1
言語: 日本語
public static GameObject[] FindGameObjectsWithTag (string tag);

パラメーター

tag GameObjects を検索するためのタグ名

説明

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

この関数を使用する前にタグマネージャーでタグの設定を行う必要があります。タグが存在しない、または空文字や null を渡した場合は UnityException の例外が発生します。

// Instantiates respawnPrefab at the location
// of all GameObjects 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 GameObjects 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 GameObjects are tagged with 'Enemy'"); } } }