Game Development Reference
In-Depth Information
A more effective search is by tag. Every object in the scene has a tag member that is
assigned Untagged by default. This member is a unique identifier that can mark a
single object or multiple objects bringing them together into a collection. Generally,
to search for objects by tag, you'll first need to explicitly assign an object with a tag.
You can do this in script, using the GameObject.tag public member. However,
you'll use the Unity Editor more commonly. You can assign a tag to a selected object
from the Unity Editor by clicking the Tag drop-down list in the Object Inspector
and picking a tag. In addition, you can create new, custom tags by selecting the
Add Tag option. Common tags include Player , Enemy , Weapon , Bonus , Prop ,
Environment , Light , Sound , and GameController , among others. Take a look
at the following screenshot:
Assigning a tag to an object
After one or more objects are assigned a tag in the scene, you can effectively
search for objects by tag in code. The GameObject.FindGameObjectWithTag
function searches the scene for an object with a matching tag and returns the
first occurrence. The GameObject.FindObjectsWithTag returns an array of all
occurrences. See the following code sample 3-4 for an example. Note that although
the FindGameObjectsWithTag function requires a string argument, Unity internally
converts the string into a numerical form to increase the speed of tag comparisons:
using UnityEngine;
using System.Collections;
//-----------------------------------------------------
public class ObjectFinder : MonoBehaviour
{
//Tag name of objects to find
public string TagName = "Enemy";
 
Search WWH ::




Custom Search