Game Development Reference
In-Depth Information
Awake()
The
Awake()
function is called when the script instance is being loaded.
Awake
is used to initialize any variable or a game state before the game starts. It is called
only once during the lifetime of the script instance. It is also called after all the objects are
initialized, so you can safely speak to other objects or query them using, for example,
GameObject.FindWithTag
. Each
Awake()
function of a GameObject is called in a
random order between objects. As a result of this, you should use
Awake()
to set up refer-
ences between scripts and use
Start()
to pass any information back and forth.
Awake()
is always called before any
Start()
function. This allows you to order the ini-
tialization of scripts.
Tip
For C# and Boo users, use
Awake()
instead of the constructor for initialization, as the
serialized state of the component is undefined at construction time.
Awake()
is called
once, just like the constructor.
Awake()
cannot be a coroutine (we will cover more about coroutines in
Appendix B
,
Coroutines and Yield
).
An example of
Awake()
is as follows:
// JavaScript user:
private var myTarget : GameObject;
function Awake() {
myTarget = GameObject.FindWithTag("Target");
}
// C# user:
GameObject myTarget;
void Awake() {
myTarget = GameObject.FindWithTag("Target");
}