1// Find the name of the closest enemyusing UnityEngine;
2using System.Collections;public class ExampleClass : MonoBehaviour
3{
4 public GameObject FindClosestEnemy()
5 {
6 GameObject[] gos;
7 gos = GameObject.FindGameObjectsWithTag("Enemy");
8 GameObject closest = null;
9 float distance = Mathf.Infinity;
10 Vector3 position = transform.position;
11 foreach (GameObject go in gos)
12 {
13 Vector3 diff = go.transform.position - position;
14 float curDistance = diff.sqrMagnitude;
15 if (curDistance < distance)
16 {
17 closest = go;
18 distance = curDistance;
19 }
20 }
21 return closest;
22 }
23}
24
1using UnityEngine;// Search for game objects with a tag that is not usedpublic class Example : MonoBehaviour
2{
3 void Start()
4 {
5 GameObject[] gameObjects;
6 gameObjects = GameObject.FindGameObjectsWithTag("Enemy"); if (gameObjects.Length == 0)
7 {
8 Debug.Log("No game objects are tagged with 'Enemy'");
9 }
10 }
11}
12
1using UnityEngine;public class Example : MonoBehaviour
2{
3 void Start()
4 {
5 //Set the tag of this GameObject to Player
6 gameObject.tag = "Player";
7 } private void OnTriggerEnter(Collider other)
8 {
9 //Check to see if the tag on the collider is equal to Enemy
10 if (other.tag == "Enemy")
11 {
12 Debug.Log("Triggered by Enemy");
13 }
14 }
15}
16
1// Instantiates respawnPrefab at the location
2// of all game objects tagged "Respawn".using UnityEngine;
3using System.Collections;public class ExampleClass : MonoBehaviour
4{
5 public GameObject respawnPrefab;
6 public GameObject[] respawns;
7 void Start()
8 {
9 if (respawns == null)
10 respawns = GameObject.FindGameObjectsWithTag("Respawn"); foreach (GameObject respawn in respawns)
11 {
12 Instantiate(respawnPrefab, respawn.transform.position, respawn.transform.rotation);
13 }
14 }
15}
16