In the previous chapter, you were introduced to a variable's scope, within which a variable exists and is allowed to be used. The scope is determined by the opening and closing curly braces. The purpose of those curly braces is to act as a container for a block of executable code—a code block. In the second chapter, you understood that a method is a code block that can execute by just calling the method's name. It's time to understand the importance of code blocks and the variables used in them. A method defines a code block that begins and ends with curly braces.
In this chapter, we will cover the following topics:
Variables are the first major building block of C# and methods are the second, so let's dive into methods.
There are two reasons to use methods in a script:
All of the executable code in a script is inside methods. The first purpose of a method is to work with the member variables of the class. The member variables store data that is needed for a component to give a GameObject
its behavior. The whole reason for writing a script is to make a GameObject
do something interesting. A method is the place where we make a behavior come to life.
The second purpose of a method is to create code blocks that will be used over and over again. You don't want to be writing the same code over and over. Instead, you place the code in a code block and give it a name so that you can call it whenever needed.
Let's take a quick look at this example:
This is a perfect example of the function that does something useful. It might look a bit strange to you as it takes two parameters. Don't worry about it too much as of now; we will cover it in detail soon. All I want you to notice right now is that the preceding method can take some data and do something useful with it. In this case, it is adding two numbers and printing the result on the Unity console. Now, the best part now—we can call this method as many times as we want, passing different parameters, without repeating the code every time we need it. If you feel confused, don't worry. Just remember that a function can save you from repeating code over and over again.
Methods can also return some data. We will cover this at a later stage in this chapter.