Game Development Reference
In-Depth Information
•
Lines 28 and 37
: The
UpdateScore
function has a return value, which is a
data type specified in line 28 before the function name. Here, the value is an
int
. This means on exiting or completion, the function will output an integer.
The integer, in this case, will be the current
Score
. This is actually output in
line 37 using the
return
statement. Functions don't have to return a value,
it's not essential. If no return value is needed, the return type should be
void
as with
Start
and
Update
.
More information on functions and their usage in C# can be found at
Events
Events are essentially functions used in a distinctive way. Both the
Start
and
Update
functions, which we have already seen, would more accurately be described
as Unity-specific events. Events are functions called to notify an object that something
significant has happened: the level has begun, a new frame has started, an enemy
has died, the player has jumped, and others. In being called at these critical times,
they offer objects the chance to respond if necessary. The
Start
function is called
automatically by Unity when the object is first created, typically at level startup. The
Update
function is also called automatically, once on each frame. The
Start
function,
therefore, gives us an opportunity to perform specific actions when the level begins,
and the
Update
function on each frame many times per second. The
Update
function
is especially useful, therefore, to achieve motion and animation in your games. Refer
to code sample 1-9, which rotates an object over time:
01 using UnityEngine;
02 using System.Collections;
03
04 public class MyScriptFile : MonoBehaviour
05 {
06 // Use this for initialization
07 void Start ()
08 {
09 }
10
11 // Update is called once per frame
12 void Update ()
13 {
14 //Rotate object by 2 degrees per frame around the Y axis
15 transform.Rotate(new Vector3(0.0f, 2.0f, 0.0f));
16 }
17 }