Game Development Reference
In-Depth Information
Variables
Variables are most often described as containers or named locations of
information. Variables can contain numbers ( integers —whole numbers
with no decimal; or float —number with decimals), on/off switches
( Booleans ), collections of text ( strings ), and XYZ values ( Vector3 ) among
others. The way scripts work is by declaring the variables that will be used
by the script at the beginning of the script (although they can be declared
in other places along the way as well). Then, the functions that follow
know of these variables and more importantly of the value that they
contain. These values can be defined, accessed, or changed in the blocks
of code that follow.
Variables are defined with a declaration statement with the var label and
should start with lowercase. They can include letters and numbers but
shouldn't start with a number. Lastly, it's important that a variable not use
the name of other reserved terms that Unity uses for other purposes (so
no naming a variable “boolean,” for example, since that is used to define a
variable type). So, for instance, a variable declaration and access could look
like this:
var litScene : GameObject;
function TurnLightsOff (){
litScene.active = false;
}
So what's happening there is the script is starting off by declaring the variable
litScene (notice it's all one word with lowercase to start and uppercase to
define each new word) and we are assigning a type with the : GameObject
(this could also be Boolean, String, int, or float ). Then, in the function
TurnLightsOff, we are deactivating this GameObject (which could be any
object in Unity) that we've given the name of litScene .
Of course, this script is pretty ineffective right now since we've defined a
function but have not told Unity when to “fire” it. It has the instructions,
but doesn't know when to use them. We would use other functions like
OnMouseDown to trigger that.
Dot Syntax
This is a very useful mechanism within Unity's JavaScript. Basically it is a
way of drilling down through objects to components and then to individual
attributes of components. It's a way of accessing information in a hierarchical
manner from biggest or most general to smallest or most specific. So for
instance if we wanted to set the rotation value of a GameObject that we have
defined (with a variable that we've named in the script as enemyTank) we
could do it like this:
enemyTank.transform.rotation.y = 60;
Search WWH ::




Custom Search