Defining Methods — Unity C#

Imran Momin
6 min readApr 14, 2021

--

In the previous article, we briefly touched on the role methods play in our programs; namely, that they store and execute instructions, just like variables store values. Now, we need to understand the syntax of method declarations and how they drive action and behavior in our classes.

Basic Syntax

As with variables, method declarations have their basic requirements, which are as follows:

· The type of data that will be returned by the method

· A unique name, starting with a capital letter

· A pair of parentheses following the method name

· A pair of curly brackets marking the method body (where instructions are stored)

Putting all of these rules together, we get a simple method blueprint:

returnType UniqueName()
{
method body
}

Modifiers and parameters

Methods can also have the same four access modifiers that are available to variables, as well as input parameters. Parameters are variable placeholders that can be passed into methods and accessed inside them. The number of input parameters you can use isn’t limited, but each one needs to be separated by a comma, show its data type, and have a unique name.

Think of method parameters like variable placeholders whose values can be used inside the method body.

If we apply these options, our updated blueprint will look like this:

accessModifier returnType UniqueName(parameterType parameterName)
{
method body
}

If there is no explicit access modifier, the method defaults to private. A private method, like a private variable, cannot be called from other scripts.

To call a method, we simply use its name, followed by a pair of parentheses, with or without parameters, and cap it off with a semicolon:

//Without parameters
UniqueName();

//With parameters
UniqueName(parameterVariable);

Defining a simple method

  1. Declare a public method with a void return type called GenerateChatacter().
  2. Add a simple Debug.Log() that prints out a character name from your favorite game or movie.
  3. Call GenerateCharacter() inside the Start() method and hit Play:

When the game starts up, Unity automatically calls Start(), which, in turn, calls our GenerateCharacter() method and prints it to the Console window.

Naming conventions

Like variables, methods need unique, meaningful names to distinguish them in code. Methods drive actions, so it’s a good practice to name them with that in mind. For example, GenerateCharacter() sounds like a command, which reads well when you call it in a script, whereas a name such as Summary() is bland and doesn’t paint a very clear picture of what the method will accomplish.

Methods always start with an uppercase letter, followed by capitalizing the first letter in any subsequent words.

Methods are logic detours

We have seen that lines of code execute sequentially in the order they are written, but bringing methods into the picture introduces a unique situation. Calling a method tells the program to take a detour into the method instructions, run them one by one, and then resume sequential execution where the method was called.

These are the steps that occur:

  1. Choose a character prints out first because it is the first line of code.
  2. When GenerateCharacter() is called, the program executes its method which prints out Character: Mario, then resumes the execution line.
  3. A good choice!! prints out last, after all the lines in GenerateCharacter() have finished running.

Specifying Parameters

Chances are our methods aren’t always going to be as simple as GenerateCharacter(). To pass in additional information, we will need to define parameters that our method can accept and work with. Every method parameter is instruction and needs to have two things:

  1. An explicit type
  2. A unique type

Method parameters are essentially stripped-down variable declarations and perform the same function. Each parameter acts like a local variable, only accessible inside their specific method.

If parameters are the blueprint for the types of values a method can accept, then arguments are the values themselves.

  1. The argument that is passed into a method needs to match the parameter type, just like a variable and its value.
  2. Arguments can be literal values or variables declared elsewhere in the class.

Argument names and parameter names don’t need to match to compile.

Adding method parameters

Let’s update GenerateCharacter() so that it can take two parameters:

  1. Add two method parameters: one for a character’s name of the string type, and another for a character’s level of the int type.
  2. Update Debug.Log() so that it uses these new parameters.
  3. Update GenerateCharacter() method in Start() with arguments, which can be either literal values or declared variables:

Here we defined two parameters, name (string) and level (int), and used them in the GenerateCharacter() method, just like local variables. When we call the method inside Start(), we added argument values for each parameter with corresponding types. In the preceding screenshot, we can see that using the literal string value in quotations produced the same result as using characterLevel.

Specifying return values

Aside from accepting parameters, methods can return values of any C# type. Being able to write instructions and pass back computed results is where methods shine.

According to our blueprints, method return types are specified after the access modifier. In addition to the type, the method needs to contain the return keyword, followed by the return value. A return value can be a variable, a literal value, or even an expression, as long as it matches the declared return type.

Methods that have a return type of void can still use the return keyword with no value or expression assigned. Once the line with the return keyword is reached, the method will stop executing. This is useful in cases where you want to avoid certain behaviors or guard against program crashes.

Adding a return type

Let’s update GenerateCharacter() method so that it returns an integer:

  1. Change the return type in the method declaration from void to int.
  2. Set the return value to level + 2 using the return keyword.

GenerateCharacter() will now return an integer. This is computed by adding 2 to the level parameter.

Using return values

When it comes to using return values, there are two approaches:

  1. Create a local variable to capture the returned value.
  2. Use the calling method itself as a stand-in for the returned value, using it just like a variable. The calling method is the actual line of code that fires the instructions, which in our example would be GenerateCharacter(“Mario”, characterLevel). We can even pass the calling method into another method as an argument if need be.

Capturing return values

We are going to use both ways of capturing and using return variables with two simple debug logs:

  1. Create a new local variable of the int type, called nextLevel, and assign it to the return value of the GenerateCharacter() method call we already have in place.
  2. Add two debug logs, with the first printing out nextLevel and the second printing out a new calling method with argument values of choice.
  3. Comment out the Debug.Log inside GenerateCharacter() with two backslashes (//) to make the console output less cluttered.
  4. Save the file and hit Play in Unity.

To the compiler, nextLevel and GenerateCharacter() method caller represent the same information, namely an integer, which is why both logs show the same output.

--

--

Imran Momin
Imran Momin

Written by Imran Momin

A VR/AR developer, who enjoys making games and developing interactive environments using Unity’s XR integration toolkit for Oculus quest and HTC vive devices.

No responses yet