Scripts as
Behaviour Components
What are scripts in Unity? Learn about the behaviour component that is Unity script and how to create and attach them to objects.
What are scripts in Unity? Learn about the behaviour component that is Unity script and how to create and attach them to objects.
So today I really wanted to begin to look at how Unity
scripting really works. After the small tutorial taken by Steve a couple of
weeks ago I was really interested in how it can be used in Unity to alter the
game objects even more. Now that I am getting to that very late stage in my
project I really want to start thinking about how I can use it effectively in
my final piece and how I can also do some more tests with it to alter weather
in Unity.
Scripts can be applied to any object. they have an example cube
that can fall to the floor in their scene and this has a rigid body on it which
means that the physics on it make it fall as if gravity where affecting it. It
also has an example script on it which changes the colour of the cube, a part
of it being:
gameObject.renderer.material.color= Colour.red;
gameObject.renderer.material.color= Colour.red;
To begin with we have the game objects which is the object
in the scene that the script is attached to, this shows the script what it is
affecting. We then have the renderer which is the mesh on the object, in this
case it is a mesh renderer. We then have the material which is applied to the
mesh renderer, and the colour is the property that we are changing on the
material, in this case the colour of it. The ending is simply what we are
changing the colour too and in this case it is simply red, as this is a colour
it knows.
We can also add a whole script that allows us to change
aspects of the game. We can create scripts in Unity by right clicking in the
projects area selecting an already existing script or creating a new one. This
script can then be taken from the asset folder and added to the objects
directly by clicking and dragging. It can also be added in by opening a new
component. The last way they can be added is selecting the object and then
choose scripts under the components menu at the top of the screen.
The whole script is featured below and this is a very useful
one that can be used for changing the colour of the game object. With this
basis, you can start to see how the cube properties can be affected in Unity
and through more understanding I can begin to look at how other things can be
changed.
using UnityEngine;
using System.Collections;
using System.Collections;
public class ExampleBehaviourScript
: MonoBehaviour
{
void Update ()
{
if(Input.GetKeyDown(KeyCode.R))
{
gameObject.renderer.material.color = Color.red;
}
if(Input.GetKeyDown(KeyCode.G))
{
gameObject.renderer.material.color = Color.green;
}
if(Input.GetKeyDown(KeyCode.B))
{
gameObject.renderer.material.color = Color.blue;
}
}
}
{
void Update ()
{
if(Input.GetKeyDown(KeyCode.R))
{
gameObject.renderer.material.color = Color.red;
}
if(Input.GetKeyDown(KeyCode.G))
{
gameObject.renderer.material.color = Color.green;
}
if(Input.GetKeyDown(KeyCode.B))
{
gameObject.renderer.material.color = Color.blue;
}
}
}
Variable and Functions
What are variables and functions, and how do they store and process information for us?
I then moved onto the next tutorial on the Unity website. Variables
are boxes that contain information and you need a different one for each bit of
information. We can use an 'int' function which stands for an integer, a whole
number. We can put this into a piece of code, give it a name and then also make
it equal a value.
int myInt = 5;
We can use a debug to be able to see how Unity reads the
line of code, so when this, along with the start up script that is already in
C# when you open up MonoDevelop, the computer will be able to debug the code
and produce an answer. So if we add this to a game object and then run it, the
debug menu will read it and then present us with the value of 5, as this is
what we have told the integer to be. When we debug we can also use other sums
as well, like make the debug run that integer but then multiply the number by
2, and we will be presented with 10.
To do something more detailed with the code we need to add
in a function, or a method. A function will take our boxes and then give us
boxes back, and this is known as 'return'.
When we make a function that doesn't give anything back, the type is
'void'. If we want it to return something to us, we have to change the setup
slightly.
We will use curly brackets around the function so that it is
all stored together. What we can see in the script below is that we have
started with this statement that says the integer in here is called myInt and
it has a value of 5. We have then started the void function, by telling it to
start. We have then said that myInt is equal to the value of this function
MultiplyByTwo(myInt). The computer does not know what the value or equation of
MultiplyByTwo is, only that myInt has the value of 5, so below we have to tell
the computer.
You can then see that we have expanded and told the computer
what the function MultiplybyTwo means. We have created a new integer, and told
it that we are going to be using another number with it, which is the integer
in the brackets next to it. We have just called this number for now as we are
going to be feeding another number into it later on. We have then used curly
brackets to define that the value of MultiplyByTwo is. We have created this
next integer and called it ret, the shortened word for return to that we know
it's going to be returning information to us. We have then given 'ret' a value,
in this case multiply by two, and we have finished off with the return
function, so that the computer knows the values need to be returned.
We now have this whole function working, and above the
Debug.log we can see that we are taking myInt and making it equal to the
MultiplyByTwo function and using the myInt value again so that it has a figure
to base the equation off.
This was very confusing for me to get my head around, but
when expanding the function and code like this, it helped me to understand the
different stages to how it works and why we need the different parts of code in
order for the whole thing to work., and work successfully.
using UnityEngine;
using System.Collections;
using System.Collections;
public class VariablesAndFunctions : MonoBehaviour
{
int myInt = 5;
void Start ()
{
myInt = MultiplyByTwo(myInt);
Debug.Log (myInt);
}
int MultiplyByTwo (int number)
{
int ret;
ret = number * 2;
return ret;
}
}
{
int myInt = 5;
void Start ()
{
myInt = MultiplyByTwo(myInt);
Debug.Log (myInt);
}
int MultiplyByTwo (int number)
{
int ret;
ret = number * 2;
return ret;
}
}
Conventions and Syntax
Learn about some basic conventions and syntax of writing code - dot operators, semi-colons, indentations and commenting.
Syntax
simply means the structure of the language. The dot operator works like writing
the line of an address, each is on a different line, and it allows Unity to
break up the elements, for example we have below a piece of script which has a
Debug.Log function it, you can see that each part is separated by dot
operators. This is helping Unity to break it up further as there are different
elements to each one. Transform has the three different movements, position,
rotate and scale associated with it, so we need to state which one we are
doing, in this case moving the position. Then again, position has 3 different
possible axis that the object can move to, x, y and z, in this case we are
moving it in the x axis and we have chosen all this by using the dot operator.
The next
piece of syntax we have is the semi-colon. The semi-colon is used to terminate
statements, which is why they are at the end of a statement. They do not need
to be at the end of curly brackets or pieces of code that are an if statement
for example.
Indenting
is an important part of writing code that makes it both presentable and
legible. It really just helps to ensure that everything matches up well. We can
do this easily by holding shift and pressing tab, this will indent the lines
selected by 1 at a time, making it simple to read down the page, as seen below.
Finally
comments can be used in a very simple way that has many different functions.
They can be used simply to leave messages to other people in our code, like if
our working with other people, or you can leave whole message in their as well.
This is done by either using //, if you want to leave on line, or /* if you
want to write over many lines, but must finished with */ otherwise the comment
will go all over the code. But this can
be good if there is a part of the code that you want to disable to test certain
parts of the code to see if their working. MonoDevelop is very helpful as it
will also change the colour of the text to green so that you can easily see
where you have comments in the code.
using UnityEngine;
using System.Collections;
public class BasicSyntax : MonoBehaviour
{
void Start ()
{
Debug.Log(transform.position.x);
if(transform.position.y <= 5f)
{
Debug.Log ("I'm about to hit the ground!");
}
}
}
using System.Collections;
public class BasicSyntax : MonoBehaviour
{
void Start ()
{
Debug.Log(transform.position.x);
if(transform.position.y <= 5f)
{
Debug.Log ("I'm about to hit the ground!");
}
}
}
C# vs Javascript Syntax
Some of the core difference between C# and Javascript syntax in Unity.
First of
all both of these scripts work equally well in running Unity and it is very much up to you as to which one
you use. Below are some of the main differences in the two from the tutorial on
the Unity website.
C# scripts
have the class declaration scripts shown but in Javascript they are hidden and
you automatically write inside the class, in C# you just have to do everything
inside of the first brackets.
C# starts with you declaring the type of variable that you are
going to be using, e.g int, you then name it, e.g myInt, and then typically
giving it a value, e.g =5. In Javascript the variable starts with using the
keyword 'var', we then name the variable, then we have the option to name the
type of variable, e.g. int, and then we can give it a value, e.g =5.
A function declaration in C# starts with a start of variable
that will return from the function, or the word void if we're not returning. So
this starts with the variable, int, you name the function, and then you have the parameters that are
changed inside, like the second script that we worked on. In Javascript a
function declaration starts with the keyword 'function' , we then name the
function, and then you add in the
parameter list. Below is what they would look like in a script respectively.
C# = returnFunctionName(type
parameterName)
JS = function FunctionName(parameterName:type) :return
JS = function FunctionName(parameterName:type) :return
The last key difference is the default access, so this is who
can access the script, and this is important if more than one coder is working
on them at the same time. The default for C# is private, and the default for JS
is public.
If Statements
How to use IF statements to set conditions in your code.
Often in coding you will need your code make a decision based on
a condition. Think about having a cup of coffee, when it's first made the water
is too hot to drink but after letting it cool slightly, the coffee if just
right to drink, but leave it too long and the coffee is too cold. We can use
code to be able to explain how this could happen.
First of all we need to set the limits of the coffee
temperature, so that the computer know what temp it has to be at what periods
of time. We can do this with a float function so that when it reaches certain
temps it will perform the void functions below with an update. After setting
the parameters we can see that there is an IF statement, this first part simply
shows us that when we hit the space bar, we can see the temperature of the
coffee, which itself is a function. So the coffee temperature is delta time,
which is the time in seconds from the last frame, so this will use the current
frame rate of any computer instead of counting down actual seconds as some
computer can have frame rate issues. We can see that after this we are
multiplying the time rate by 5f which means that we are moving the frame rate
on per frame instead of per second, just to speed it up.
We can next see that we are doing a void function and calling it
TemperatureTest, this is then what is imputed into the update that tells us the
temperature once we push space, but again, this is just an empty function so we
need to define what is going to happen when space is pushed. We can provide the
computer with an IF statement that essentially says it the coffee's temperature
is greater than the hottest drinking temperature then print what is below.
We can then combat this with an else statement that will work
with the IF statement and say, well if it's not too hot then do this instead.
So we can then tell the computer to print coffee is too cold when the coffee
temperature is less than the coldest drinking temperature. Then, what we can
do, is add in a third option.
So as we have a higher than and a lower than option we need one
in between so that when none of the other options work as the coffee is the
right temperature we can add in the final else statement that simply reads just
print that the coffee is right. We do not need parameters for this functions
there is no figures it needs to be above or below it simply need to be any
other option other than too hot or cold.
This is a really nice way to visualise how IF statements work
and can be used, and simplifying them down to something that everyone can
relate to. It's a really nice way of looking at it and I will definitely be
trying to do this myself now that it's understandable.
using UnityEngine;
using System.Collections;
public class IfStatements : MonoBehaviour
{
float coffeeTemperature = 85.0f;
float hotLimitTemperature = 70.0f;
float coldLimitTemperature = 40.0f;
void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
TemperatureTest();
coffeeTemperature -= Time.deltaTime * 5f;
}
void TemperatureTest ()
{
if(coffeeTemperature > hotLimitTemperature)
{
print("Coffee is too hot.");
}
else if(coffeeTemperature < coldLimitTemperature)
{
print("Coffee is too cold.");
}
else
{
print("Coffee is just right.");
}
}
}
using System.Collections;
public class IfStatements : MonoBehaviour
{
float coffeeTemperature = 85.0f;
float hotLimitTemperature = 70.0f;
float coldLimitTemperature = 40.0f;
void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
TemperatureTest();
coffeeTemperature -= Time.deltaTime * 5f;
}
void TemperatureTest ()
{
if(coffeeTemperature > hotLimitTemperature)
{
print("Coffee is too hot.");
}
else if(coffeeTemperature < coldLimitTemperature)
{
print("Coffee is too cold.");
}
else
{
print("Coffee is just right.");
}
}
}
No comments:
Post a Comment