Game Development Reference
In-Depth Information
Save and play. The output in the console will look like Figure 2-22 :
Figure 2-22. Results output from arithmetic operators
You probably recognize the first four operators. The modulus operator is another handy one that
gives you the remainder, in this case the remainder of 6 divided by 2. Try changing the 6 to a 5, save,
and play. This time the last line of output is 1, the remainder of 5 divided by 2.
Like most programming languages, UnityScript follows the standard order of operations where
multiplication and division are given precedence over addition and subtraction.
Alter your Start function to the following:
print(6+2*4);
Reading from left to right, the sum of 6 and 2 is 8, which multiplied by 4 is 32. Save and play, and
you'll see that Unity multiplied 2 by 4 first to get 8, then added 6 for an output of 14.
You can change the order of evaluation by using parentheses. Operations inside parentheses are
given higher precedence. Change the same line of code as follows:
print((6+2)*4);
Now when you save and play, your output is 32 because Unity performed the addition operation
inside the parentheses first.
These same arithmetic operators can be used on numerical values held by variables. Replace the
same line of code with this statement:
print(myVar + myVar);
With the previously assigned value of 8 for myVar , now you will get 16 as the result.
So far you have been working with integers, but you can also declare a variable as a float data type
to handle decimal digits. Variables can contain all sorts of data types, including string , boolean , and
more complex data types. In fact, you used a string in your very first line of code:
print("Hello World!");
 
Search WWH ::




Custom Search