Understanding Methods — Unity C#

Imran Momin
3 min readApr 10, 2021

--

How do we go about creating actions and driving behavior in our code? The short answer is by using Methods.

Methods drive actions

Similarly to variables, defining programming methods can be tediously long-winded or dangerously brief; here’s another three-pronged approach to consider:

· Conceptually, methods are how work gets done in an application.

· Technically, a method is a block of code containing executable statements that run when the method is called by name. Methods can take in arguments (also called parameters), which can be used inside the method’s scope.

· Practically, a method is a container for a set of instructions that run every time it’s executed. These containers can also take in variables as inputs, which can only be referenced inside the method itself.

Taken all together, methods are the bones of any program — they connect everything and almost everything is built off their structure.

Methods are placeholders too

Let’s take an oversimplified example of adding two numbers. When writing a script, we are essentially laying down lines of code for the computer to execute in sequential order. The first time we need to add two numbers together, we just force it like in the following code block:

someNumber + anotherNumber

But then we conclude that these numbers need to be added together somewhere else. Instead of copying and pasting the same line of code, which results in sloppy or “spaghetti” code and should be avoided at all costs, we can create a named method that will take care of this action:

AddNumbers
{
someNumber + anotherNumber
}

Now AddNumbers is holding a place in memory, just like a variable; however, instead of a value, it holds a block of instructions. Using the name of the method (or calling it) anywhere in a script puts the stored instructions at our fingertips without having to repeat any code.

If we find writing the same lines of code over and over, we are likely missing a change to simplify or condense repeated actions into common methods.

This produces what programmers jokingly call spaghetti code because it can get messy. We also hear programmers refer to a solution called the Don’t Repeat Yourself (DRY) principle, which is a mantra we should keep in mind.

Creating a simple method

1. Create a script in Unity, and name it “LearningCurve”.

2. Double-click on the script to open it and add lines 7, 8, 13 and, 22–25.

3. Save the file, and then go back and hit Play in Unity to see the new Console output.

We defined our first method on lines 22 to 25 and called it on line 13. Now, whenever ComputeAge() is called, the two variables will be added together and printed to the console.

--

--

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