GameObject.FindGameObjectsWithTag 查找标签的游戏物体列表

static function FindGameObjectsWithTag (tag : string) : GameObject[]

Description描述

Returns a list of active GameObjects tagged tag. Returns null if no GameObject was found.
Tags must be declared in the tag manager before using them.

返回一个用tag做标识的活动的游戏物体的列表.如果没有找到则为空。
标签必须在使用之前到标签管理器里面声明。

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
	public GameObject respawnPrefab;
	public GameObject[] respawns = GameObject.FindGameObjectsWithTag("Respawn");
	public void Awake() {
		foreach (GameObject respawn in respawns) {
			Instantiate(respawnPrefab, respawn.transform.position, respawn.transform.rotation);
		}
	}
}
// Instantiates respawnPrefab at the location
// of all game objects tagged "Respawn".
//在标签为"Respawn"的全部游戏物体自身坐标实例化respawnPrefab
var respawnPrefab : GameObject;
var respawns = GameObject.FindGameObjectsWithTag ("Respawn");
for (var respawn in respawns)
Instantiate (respawnPrefab, respawn.transform.position, respawn.transform.rotation);

另一个例子:

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
	GameObject FindClosestEnemy() {
		GameObject[] gos;
		gos = GameObject.FindGameObjectsWithTag("Enemy");
		GameObject closest;
		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;
	}
	public void Awake() {
		print(FindClosestEnemy().name);
	}
}
// Print the name of the closest enemy
//打印最靠近敌人的名字
print(FindClosestEnemy().name);

// Find the name of the closest enemy
//查找最靠近敌人的名字
function FindClosestEnemy () : GameObject {
	// Find all game objects with tag Enemy
	//查找标签为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;
}
最后修改:2010年12月13日 Monday 19:15

本脚本参考基于Unity 3.4.1f5

英文部分版权属©Unity公司所有,中文部分© Unity圣典 版权所有,未经许可,严禁转载 。