Cookies   I display ads to cover the expenses. See the privacy policy for more information. You can keep or reject the ads.

Video thumbnail
Hello, everyone, in this episode. We're going to be working a bit with methods and variables
and basically just getting comfortable programming with them
So, here in unity
I've got my custom layout set up from the previous episode
And [I'm] just [gonna] head over to the project window and right click, [then hover over] Create and [select] (new) C# script.
And... I'll just call this something like Episode4 and
We can double click to open that up in MonoDevelop
So, this is the default text that were faced with when we create a new script in unity
Don't worry by the way if your colors are different from mine. This is just something that we can, customize
under syntax highlighting in the preferences and obviously, it doesn't change the way that the code behaves at all
Uhh... So most of the things here you should be familiar with, from the first few episodes
For example, the class keyword followed by the name of the class in Episode4, and then the colon [followed by] MonoBehaviour, [and] we discussed
it means that it inherits from MonoBehaviour
which just gives us some... base functionality, for example, the Start method which gets called automatically at the start of the game
and the Update Method which gets called once per frame while the game is running
remember that the Void Keyword means that these methods don't return anything and
Any text that follows a double slash on the same line is just a note that we can leave either to ourselves
Or... to other programmers [for] explaining what a bit of code does
The only things that we haven't talked about are these two lines at the top here which are called
namespaces, and for the time being we are going to ignore those
(btw namespaces are
So, to start with I'd like to look at how we can print stuff to the Unity console so... MonoBehaviour has a print method
So, if we just write the word print you can see the IntelliSense tool seemed to give us some information about print... for example
It's a public static void
and it takes in an
object for the message and it's got this little summary here as well. "It logs message to the Unity console."
So, that sounds like what we want. So if we [type] open parenthesis. We now need to pass in an object and
Turns out in C#. We'll talk more about this later, but most things are objects. So for example, we can pass in a string
Uhh... So let's just write start
So just the word start inside of quotation marks then close the parentheses
And remember to add a semicolon for the end of the line. And do a similar thing in the Update method.
Print [then type] open parentheses. Let's print the word
Update and
close parentheses semicolon, so now if we save
And go into Unity, we're going to want to attach the script to an object in our scene
So let's create a new empty game object and just drag that onto the object
We'll see it pops up in the inspector here
And then if we press play, you can see that this is being printed out into the console, and if we just toggle
collapse then you can see a nice condensed view of it, and you can see update has been printed by now 500 times
So it's being printed every frame as we'd expect
Let's go back into our Episode4 class, and let's quickly discuss something called variable scope
So say I were to create a variable inside of a method let's say the start method and I'll just create an integer variable
So... [type] int x and assign the value of 0
What happens now is when this method is run the integer x is created...
But then as soon as the method has finished running the variable x is destroyed from the computer's memory
because of this it will only create a variable inside of a method if we want to temporarily store some information for use in a
calculation for example
We call x a local variable. It was created between this opening and closing pair of braces
So it is local, in other words, It can only be used by a code which also exists between that same pair of braces
If I try access it from somewhere else say the Update method. [I'm typing] x =
5; we get this little error saying that x doesn't exist in the current context
So just to hopefully drive this point home. Say I create an opening and closing pair of braces
This defines a new local scope so I can still access x in here. [I'm typing] x = 5; for example
Because this is part of the scope in which x was defined, however, if I create an integer
y inside of here
I cannot use y outside of this pair of braces if I did try say y = 5; out here for instance...
We'd get the same error again because y no longer exists
So because local variables get destroyed at the end of their scope
We obviously can't use them to keep track of things across the entire game such as the player's health
So what we can do instead is create a variable like that
outside of any method usually at the top of our class.
Let's use the example of keeping track of the number of frames that have passed in our game
So I'll create an integer called frameCount and notice the convention for naming variables,
we start with a small letter and then each subsequent word starts with a capital letter
We can say frameCount equals 0 and just to give a bit of terminology
This part where we give the name of the variable and the type of the variable is called the variable
declaration. Here where we give it its initial value is called the initialization
When we're creating these
non-local variables the initialization is optional if we leave this out it will get initialized to its default
value, which for integers is zero
So now to count the number of frames
We're just going to go into the update method since that's called once per frame and add one to the frame count
So we can say frameCount is equal to frameCount plus one.
Now, there is a shorthand way of writing this which is simply frameCount += 1;
This is saying that one gets added to the original value. So you'll generally see this instead because it's of course much shorter
Let's now print out our frame count. So we can say, frame count
Then let's save this and go into unity to run it
and we can see that now our frame count gets printed out over here.
If we wanted to print the words frame count next to it. We could add quotation marks
[I'm typing] Frame Count:
And then we just say plus. So the plus operator is not only for numbers
We can also add things onto strings. So here we're adding the value of frameCount onto this frameCount string
Let's save that and run.
And you can see that working in the bottom right here
Alright, so we've briefly touched on variables
Let's now take a look at a practical example of a method. So say we want a method to calculate the distance between two points
So if we're given two points defined by the coordinates (X1, Y1) and (X2, Y2)
We can, of course, use Pythagoras' Theorem to find the distance,
so we'd say the change in X, or delta X is equal to X2 minus X1 and
The Delta Y is equal to Y2 minus Y1 and then the distance is the square root of Delta X squared plus Delta Y squared.
So in our code we'll want this method to return the value of the distance, so we'll give it a return type of
float and then we can call this method something like GetDistanceBetweenTwoPoints
Notice the naming convention for our method here
It's exactly the same as variables except the first letter is a capital
You might wonder why Unity hasn't followed this naming convention for their print method?
And I'm not sure but don't use that as an excuse to not follow the convention yourself
Let's now create our opening and closing parenthesis followed by the opening and closing braces
So we'll want to pass the coordinates of the two points into this method
So hopefully you remember we can declare the variables inside of these parentheses here
So we say float x1 comma float Y1
and then 4.2. We'll say float x2
comma float y2
So now we can create a local variable
Delta X is equal to x2 minus x1 and
float Delta Y is equal to y2 minus y1
So next we'll want to create a float called something like distance squared and set that equal to
Delta X times Delta X plus DeltaY times Delta Y
All right, so we've got the squared distance in order to get the
Actual distance we now want to get the square root of distance squared so to get the square root.
we can use something called Mathf which as you can see over here is a
Struct which we haven't learned about yet, but in this case it behaves pretty much identicaly to a class
So this has a method called
Square root which as you can see from this pop-up takes in a float f and returns the square root of that number
So it's returning a float so we can set our float distance variable directly to the result of this method
so math f dot square root (Mathf.Sqrt) of
distance squared
All right, all we need to do now is return the distance
So we write the return keyword followed by distance and as always don't forget the semicolon
All right, so now say in the start method. We wanted to set float distance
equal to [you can] say get the distance between two points
and it's generated this little pop-up for us saying that this method returns a float takes in x1 y1 x2 and y2 and
We can pass in say
(0, 5) and then our second point could be
10 and 15
and just like that we found the distance. Let's print it out. So print distance
Alright let's save and see what that distance happens to be
Uhh... let me just
Comment out this print frame count line otherwise, that's going to get lost in the wall of text
So just remember to save of course and then press play
so that distance happens to be 14.14214
Before we end off for this episode
I'd like to give an example of what happens if we make a mistake in our code say for example
I forget the semicolon at the end of this line, so I'll delete that
Save, and go into unity you can see this error message pop up in the console saying
"Unexpected symbol 'float' " and if we double-click on the error message it will take us to where the error is occurring.
Now, the reason it's saying "Unexpected symbol 'float' " is
It doesn't really care about paragraphs
it's reading this as being one line and
This doesn't make sense Delta X times Delta X plus Delta Y times Delta Y float; you can see why the float symbol was?
It doesn't make sense here
So from this we can figure out that we need to add the semicolon after
Delta y, so that it knows that the line ends there
So that's one example of an error that could occur let's look at one more example
say we forget to make this a
float and instead we say that it's a Void method
But we're still trying to return the distance if we now save and go into Unity we can see that
We actually have three errors now, but they're all being caused by the same thing
So we will start with the topmost error message, and we can see this one saying "Cannot implicitly convert type 'void' to 'float' "
Let's double click on that and it says the error is coming from here because we tried to set a float variable,
equal to a method which returns void so from that we can immediately tell, that this
should be, a float and if we save and go into Unity, of course, all three of those error messages have now disappeared
Alright, that's everything for this video
I encourage you to practice what you've learnt of methods and variables so that you can get comfortable working with them.
Until next time, cheers.