C# Methods allow us to organize and our code into named, logical, sections. As our C#/Unity game projects become more and more advanced with exciting features and deep systems, methods will be one of the constructs that make it possible. We have already seen the Unity
Start method in the Unity & C# part 1 project. Here we will dig a little deeper into how methods can help us code our games.
[widgets_on_pages id=”udemy_advert_unity_1″][widgets_on_pages id=”udemy_code_details”]
What exactly are C# methods?
A method is a collection of variables, expressions, loops and condition checks ( if statements). The first part of a method that we write is called the signature. Here is an example method signature.
public void fireBlasters(int power, int direction)
Add an opening and closing pair of curly braces {} with some code that the method performs and we have a complete method, a definition.
public void fireBlasters(int power, int direction) // ZAPP! }
We could then use our new method from another part of our code like this:
// Just going to shoot some lazers fireBlasters(100, 45) // Run the code in the method // I'm back again - code continues here
When we use a method we say that we call it. At the point where we call fireBlasters, our program’s execution branches to the code contained within that method. The method would run until it reaches the end or is told to return. Then the code would continue running from the first line after the method call. Here is another example of a method complete with the code to make the method return to the code that called it.
int addAToB(int a, int b){ int answer = a + b; return answer; }
The call to use the above method could look like this:
int myAnswer = addAToB(2,4);
As we know, we don’t need to write methods to add two variables together but the example helps us see a little more into the workings of methods. First we pass in the values 2 and 4. In the method signature the value 2 is assigned to int a and the value 4 is assigned to int b.
Within the method body, the variables a and b are added together and used to initialize the new variable int answer. The line return answer; does just that. It returns the value stored in answer to the calling code causing myAnswer to be initialized with the value 6.
Notice that each of the method signatures in the examples above varies slightly. This is a reflection of the fact that the C# method signature is quite flexible and allows us to build exactly the methods we require.
Exactly how the method signature defines how the method must be called and if/how the method must return a value deserves further discussion. Let’s give each part of that signature a name so we can break it into chunks and learn about them.
Here is a method signature with its parts described by their formal technical term.
modifier | return type | name of method (parameters)
And here are a few examples we can use for each of those parts. There is one completely new concept here as well, the modifier.
C# method signature Examples
Modifier:
public,
private.
Return type:
int, also use (
bool,
float, etc, any C# type, expression or object)
Name of method:
fireBlasters,
loadSaveGame,
addAToB, whatever.
Parameters:
(int number, String type),
(int x, int y),
(int a, int b)
Now let’s look at each part in turn.
[widgets_on_pages id=”udemy_advert_games_category”][widgets_on_pages id=”udemy_code_details”]
Method modifiers
The method doesn’t have to use the modifier but the modifier (eg. public and private) is a way of specifying what other code can use your method. In C# if a modifier isn’t specified then the default of private is used. We will talk more about modifiers and reveal that in fact variables can have modifiers too, when we enter the world of C# classes and objects in the Object Oriented Programming C# tutorial.
Return types
Like a modifier a return type is optional as well.
int addAToB(int a, int b){ int answer = a + b; return answer; }
In the previous code the return type in the signature is int. The method addAToB sends back/returns to the code that called it, a value that will fit in an int variable. The return type can be any C# type we have seen so far or one of the ones we haven’t seen yet ? . The method does not have to return a value at all, however. In this case the signature must use the void keyword as the return type. When the void keyword is used the method body must not attempt to return a value as this will cause an error. It can however use the return keyword without a value.
Here are some combinations of return type and use of the return keyword that are valid. Be sure to read the code comments that explain further.
void doSomething(){ // our code // I'm done going back to calling code here // no return is necessary }
Another possibility is as follows:
void doSomethingElse(){ // our code // I can do this as long as I don't try and add a value return; }
The following code is yet another couple of possible methods:
void doYetAnotherThing(){ // some code if(someCondition){ //if someCondition is true returning to calling code //before the end of the method body return; } //More code that might or might not get executed return; // As I'm at the bottom of the method body // and the return type is void, I'm // really not necessary but I suppose I make it // clear that the method is over. } String joinTogether(String firstName, String lastName){ return firstName + lastName; }
We could call each of the methods above, in turn, like this:
// OK time to call some methods doSomething(); doSomethingElse(); doYetAnotherThing(); String fullName = ("Jeff ","Minter") // fullName now = Jeff Minter // continue with code from here
Method names
The method name when we design our own methods can be almost anything at all. But it is best to use words that clearly explain what the method will do. Take a look at this method name.
XcbyUooooooMMvdfrsse2(){ //code here that does something }
The previous method is perfectly legal and will work but what will it do? The name doesn’t help us at all. These next methods are much clearer.
doSomeVerySpecificTask(){ //code here } getMySpaceShipHealth(){ //code here } startNewGame(){ //code here }
Another example of good method names is the Unity Start method. It is called, at the start. Simple.
Method parameters
We know that a method can return a result to the calling code but what if we need to share some values from the calling code with the method? Parameters allow us to share values with the method. We have actually already seen an example when looking at return types. We will look at the same example but a little more closely.
int addAToB(int a, int b){ int answer = a + b; return answer; }
In the previous method, the parameters are int a and int b. Notice that in the first line of the method body we use a + b as if they are already declared and initialized variables? Well, that’s because they are. The parameters in the method signature is their declaration and the code that calls the method initializes them.
int returnedAnswer = addAToB(10,5);
Also as we have partly seen in previous examples, we don’t have to just use int in our parameters. We can use any valid C# type. We can even use types that we invent ourselves(more in the tutorial Object Oriented Programming in C#). We can also use as many parameters as is necessary to solve our problem. Perhaps like this next hypothetical method.
void addToAddressBook(char firstInitial, String lastName, String city, int age){ //all the parameters are now living breathing, //declared and initialized variables //code to add details to address book database goes here }
We have already seen the Start method in Unity. Here is the signature of the Start method
void Start();
The Start method has no parameters and does not return any value( void). The big point to be aware of with the Start method in the context of this tutorial is the following. Although we write the code which goes in the Start method, it is Unity which calls the Start method, when appropriate. In Unity and other game engines you often provide the code for a method which the engine is in charge of calling.
The method body
The method body is the part we have been mainly avoiding with comments like:
// code here // some code
But actually we know exactly what to do here already. Any C# code we have learned already will work in the body of a method.
There is a common mistake for beginners coding there own methods so let’s learn about scope.
Variable scope
If we declare a variable in a method it is said to be in scope for that method. This means that outside of the method it cannot be seen and therefore its value cannot be used or accessed. There are a number of ways around this problem.
- We can write code that enables the variables value to be shared with other parts of the code.
- We can declare variables outside of methods to widen their scope.
- We can pass variable values between methods with parameters and return types(as we have just been discussing).
These concepts are explored a bit more when we learn about Object oriented programming in C# but we will really get to grips with this during the practical Unity projects.
There is much more we could learn about methods but we know enough about them already to make another project in Unity. And don’t worry if all the technical terms like parameters and signatures etc. have not completely made sense. The concepts will become clearer when we start to use them.
Let’s move on to do our second practical Unity project Unity & C# part 2.
Good stuff so far, cheers!
(I meant to ask here instead of the other thread, sorry. But was part 2 ever released? The text in the paragraph, doesn’t link to any tutorial, and I don’t see it available anywhere.)
Really sorry. I got Google whacked shortly after writing this and I got so few visitors I kind of gave up