Game Development Reference
In-Depth Information
function allows for control over when a collection of commands are actually
called on. For instance, if we're pulling a power switch, we only want
the animation to play when the character clicks the power switch on; by
grouping the collection of commands that do this into a function, we can tie
that function to a player's action (like clicking an object).
Any script may contain multiple functions. Some functions just are named by
you, the scripter, but there are also some predefined functions in Unity that
dictate how a block of code will be carried out, or more importantly, when.
These include things like function Update() , which means, “do these
instructions every frame of the game,” and function OnMouseDown() , which
means, “do these instructions when the player clicks on the object this script is
attached to.” Much more on these later.
The key to writing functions is to remember all the appropriate punctuation
hints. The format works like this:
function TurnSoundOff(){
audio.enabled = false;
}
We tell Unity we're building a function named TurnSoundOff with function
TurnSoundOff and tell it there are no particular parameters for the function
with the empty () . Then Unity knows we're starting the block of commands
for this function by the { . Then, the command audio.enabled = false ; is
included and ended with a semicolon. Finally, we tell Unity we're done with
this function by ending it with a } .
Capitalization matters. “function” is not the same as “Function”. When defining a
function, always use lowercase function. Generally, the name of the function is
capitalized. The organization of this example block of code is mostly for readability.
The closing } is at the same indentation as the function (so it's easy to see that the
function has been closed. However, technically, it could also look like this:
function TurnSoundOff()
{audio.enabled = false;}
which is really tough to read, or like this:
function TurnSoundOff()
{
audio.enabled = false;
}
which is easier still to see how the function is created, but can make the code
very long and difficult to read in the topic. Usually, the way code is formatted
is with the fairly standard:
function TurnSoundOff(){
audio.enabled = false;
}
Search WWH ::




Custom Search