In C# Methods and Functions are exactly the same. In other languages it’s called a function but ultimately they’re one and same. So what is the structure of a method? Let’s take a look. When you create a new Unity script you actually get two methods built-in Start() and Update().
Methods have four components: accessors (public, private, protected, etc. This is optional but by default it is private), return type (void is the default and returns nothing), method name (for example “MyMethod”), and parameters. (with a blank () by default). So how do you use a method in your script? That’s pretty easy as well as illustrated below.
We simply just call the method itself and then the empty parameters followed by a semi-colon. When using a method with no parameters that’s all you need to do. In the case of the void return type the method just executes the statements from top to bottom. This lets your tidy up your code and modularize it. It also allows you to almost blueprint or create the framework of your code by letting you organize the major mechanics of that class for example like saying “Well I need a Attack method, and then a Powerup method, and then a Death method” and so forth.
The next feature of Methods is the ability to pass in parameters or arguments, this give methods the ability to take those parameters and use them in the method. An example would be something like a damage system when you take in a damage value and then apply it to the player’s health.
Here’s a more complicated example where we take a Game Object and then pass it in and change it’s color via the inspector at when the game runs. Here’s what it should look like.
Here’s the associated code. Pretty easy to follow, create a method that passes in a Game Object parameter and then a color parameter that runs in Start().
The final feature of a method is the return type, this allows you to return the specified data back after the method is done running its statements. In this example we have an int return type on the Add() method that takes two parameters. It then returns the sum total which we define to sum1 and sum2 in the start.
Here’s the final result in the console.
You can return any sort of data back if the method is defined it in the return type. Game Objects, ints, bools, strings, your name it and it can be returned. Even custom data types you create. Return types help constrain the kind of data that returns so you’re not using a method that has a specific purpose.
As you can see methods provide a wide swath of tools and organization for your increasingly complex projects. No longer will you have a 5000 line Update() method that holds all your code. Now go out there and modularize your code so that you don’t peel your eyelids trying to troubleshoot an errant line of code. Until next time, happy coding.