Game Development Reference
In-Depth Information
Finding GameObjects
Finding an object in the scene can be achieved through either the GameObject.Find
or GameObject.FindObjectWithTag function. Of these two, the latter should
almost always be preferred for performance reasons. However, let's consider
GameObject.Find first. This function searches the scene for the first occurrence
of an object with an exactly matching name (case-sensitive) and then returns that
object. The name that's searched should match the object name as it appears in
the Hierarchy panel. Unfortunately, the function performs string comparisons to
determine the match, so it's a slow and cumbersome option. Besides, it's only truly
effective for objects guaranteed to have unique names, and many times, objects won't
have. However, that said, GameObject.Find is still highly useful when objects are
appropriately named:
//Find Object with the name of player
ObjPlayer = GameObject.Find ("Player");
GameObject Finding
If you notice the GameObject , you would realize that the Find function
is static. This means that you don't need an instantiation of any specific
GameObject to call the function. You can call it directly from any source
file via GameObject.Find . The concept of static and global scope is
considered later in this chapter.
More information on the GameObject.Find function can be found
in the online Unity documentation at http://docs.unity3d.com/
ScriptReference/GameObject.Find.html .
GameObject.Find can be a slow function. For this reason, use it only
inside one-fire events, such as Awake and Start .
 
Search WWH ::




Custom Search