unity3d Finding GameObjects by Tag:


Example

Tags make it particularly easy to locate specific game objects. We can look for a single game object, or look for multiple.


Finding a Single GameObject

We can use the static function GameObject.FindGameObjectWithTag(string tag) to look for individual game objects. It is important to note that, in this way, game objects are not queried in any particular order. If you search for a tag that is used on multiple game objects in the scene, this function will not be able to guarantee which game object is returned. As such, it is more appropriate when we know that only one game object uses such tag, or when we are not worried about the exact instance of GameObject that is returned.

///<summary>We create a static string to allow us consistency.</summary>
string playerTag = "Player"

///<summary>We can now use the tag to reference our player GameObject.</summary>
GameObject player = GameObject.FindGameObjectWithTag(playerTag);

Finding an Array of GameObject instances

We can use the static function GameObject.FindGameObjectsWithTag(string tag) to look for all game objects that use a particular tag. This is useful when we want iterate through a group of particular game objects. This can also be useful if we want to find a single game object, but may have multiple game objects using the same tag. As we can not guarantee the exact instance returned by GameObject.FindGameObjectWithTag(string tag), we must instead retrieve an array of all potential GameObject instances with GameObject.FindGameObjectsWithTag(string tag), and further analyse the resulting array to find the instance we are looking for.

///<summary>We create a static string to allow us consistency.</summary>
string enemyTag = "Enemy";

///<summary>We can now use the tag to create an array of all enemy GameObjects.</summary>
GameObject[] enemies = GameObject.FindGameObjectsWithTag(enemyTag );

// We can now freely iterate through our array of enemies
foreach(GameObject enemy in enemies)
{
    // Do something to each enemy (link up a reference, check for damage, etc.)
}