Graphics Reference
In-Depth Information
12.3.2.1 Script Breakdown
The RaceController.cs script is going to be tracking everything we need for a race game
(other than players). It derives from MonoBehavior so that it can tap into the automated
system calls to Update(), Start(), etc.:
using UnityEngine;
using System.Collections;
public class RaceController : MonoBehavior
{
Every racer will be given a unique ID by the global race manager (covered later in this
chapter). When the script is on its first run, the myID variable is set to −1 so that any other
scripts trying to access it will instantly know that it is not ready to be accessed. Once the
script's Init() function has completed, the ID should no longer be −1, and it should be set
correctly:
// we default myID to -1 so that we will know if the script hasn't
// finished initializing when another script tries to GetID
private int myID =-1;
RaceController() is automatically called by the engine when the script is first
instanced. To get the player set up with an ID number as soon as possible before the race
actually begins, myID is set up in the constructor (whereas it might normally be set a little
later on in the Init() function).
To get a unique ID, the global race manager contains a function called GetUniqueID().
The logic behind this function ensures that each player will be awarded a unique ID
at the start of each game. Its ID may then be used to identify it elsewhere. Note that
GlobalRaceManager.Instance is a static variable. The race manager uses some nifty code
to ensure that there is only ever one instance of the script in action at any time, which will
be looked at in detail later on in this section, so don't worry about that just now.
myID is an integer, set by a call to GlobalRaceManager.Instance.GetUniqueID(). The
parameter it takes is this instance of the script, so that the race manager will be able to link
the ID to the script from here on:
public RaceController ()
{
myID= GlobalRaceManager.Instance.GetUniqueID( this );
Debug.Log ("ID assigned is "+myID);
}
Init() grabs a cached reference to myTransform and sets its doneInit Boolean to true:
public void Init()
{
myTransform= transform;
doneInit= true;
}
Search WWH ::




Custom Search