GameObjects and the world
Another pivotal task in Unity involves searching for objects in the scene from script, especially if objects are instantiated at runtime. Tasks such as "get me the player object" and "get me all enemies in the scene" are important for many operations, from respawning enemies and power-ups to repositioning the player and checking collisions between objects. To retrieve references to specific GameObjects
, Unity offers a set of functions associated with the GameObject
class. These functions can be useful but expensive, so be sure to call them during one-off events, such as Start
and Awake
, wherever possible. Let's explore these further, in addition to other techniques and methods to work with found objects.
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...