Game Development Reference
In-Depth Information
Awake versus Start
The GameManager class uses the Awake function, as opposed to
Start , in code sample 3-12. The difference between Start and
Awake is as follows:
Awake is always called before Start .
Awake is always called at object creation. Start is called on the first
frame in which the GameObject becomes active. If a GameObject
starts the scene deactivated, then Start will not be called until the
object is activated. For objects that are activated by default, Start is
called at the beginning of the scene, after the Awake event.
If you need to cache component references into local variables of a
class, such as the Transform component in ThisTransform , then
use the Awake event rather than Start . During the Start event,
the assumption should be that all local references to objects are
already valid.
The great benefit of having a global, static Instance property for GameManager
is that it becomes instantly and directly accessible to any other script file, without
the need for any local variables or object references. This means every class has
instant access to all GameManager properties and can call upon high-order game
functionality. For example, to set the game score variable on the GameManager
from a different class, the following code sample 3-15 can be used:
using UnityEngine;
using System.Collections;
//-------------------------------------------
public class ScoreSetter : MonoBehaviour
{
//-------------------------------------------
// Use this for initialization
void Start ()
{
//Set score on GameManager
GameManager.Instance.HighScore = 100;
}
//-------------------------------------------
}
//-------------------------------------------
More information on singleton objects can be found online at
http://unitypatterns.com/singletons/ .
 
Search WWH ::




Custom Search