Game Development Reference
In-Depth Information
//Array of found objects matching tag
public GameObject[] FoundObjects;
//-----------------------------------------------------
// Use this for initialization
void Start ()
{
//Find objects of matching tag
FoundObjects = GameObject.FindGameObjectsWithTag(TagName);
}
}
//-----------------------------------------------------
Sometimes, you'd like to assign multiple tags to a single object.
Unfortunately, Unity doesn't support this behavior yet. However, you
can work around the limitation by parenting empty game objects to your
main object and assigning each of the children the tag you need. When
searching for objects by tag, though, just remember to get a reference to
the parent object, which is actually the object you need.
Comparing objects
The GameObject searching functions are helpful when searching scene-wide for
specific objects, but there are times when you'll need to compare two objects that
you've found already. Typically, you'll want compare the names or tags of two
objects. You can achieve a tag comparison using the CompareTag function:
//Compares tag of this object with another Obj_Y
bool bMatch = gameObject.CompareTag(Obj_Y.tag);
In addition, you'll sometimes want to compare two objects for equality to determine
whether they're the same object and not simply whether they share the same tag.
This is especially important when coding decision-making behaviors. For example, in
determining whether an enemy character should fight or flee from the player during
combat, it'd be helpful to ascertain whether the enemy has supporting units nearby
to help him. To answer this, you can find all enemies in the scene with a tag search,
as we saw earlier. However, the results will also include the enemy who made the
call originally and who is now deciding what to do, so we'll want to exclude him
from the results. Code sample 3-4 demonstrates how GetInstanceID can help us:
 
Search WWH ::




Custom Search