Understanding Methods in C#

Objective: Properly create a method and call it in the Start method.

Natalia DaLomba
Dev Genius

--

In C#, there’s no difference at all between methods and functions. They’re interchangeable. In C#, we typically call them methods — in other languages, they’re usually called functions.

A method is an encapsulated piece of code. Examples of this are the Start and Update methods. In Unity, when we enter play mode, these methods automatically get run if we have them in our script — even if there’s no code in them. We can also write our own methods.

One of the many benefits of writing methods is it organizes and modulates your code. In turn, this makes it much easier to debug. Adding Debug lines in case there’s a null reference exception is key as you test your code. This is also for any sort of error — because it will help you understand exactly where you need to look to fix the bug in a timely manner.

You can change the access modifier (also known as type or member) for your method. For example, if you just want the method to be called within the script it was created in, then you can keep it private. If you’d like to enable script communication and call that method from another script or struct, you would use public to access it. There are other access modifiers such as:

  • protected: Accessed only by code in the same class, or in a class that is derived from that class.
  • internal: Accessed by any code in the same assembly, but not from another assembly. In other words, internal types can be accessed from code that is part of the same compilation.
  • protected internal: Accessed by any code in the assembly in which it’s declared, or from within a derived class in another assembly.
  • private protected: Accessed by types derived from the class that are declared within its containing assembly.

Both the Start and our MyMethod methods have a void return type which means the method does not return a variable once the method is done running. So the computer will continue to run through the code in your script. Note: Code always runs from top to bottom.

public class Example : MonoBehaviour {
private void Start() {
Debug.Log("Start is being called");
MyMethod();
}

private void MyMethod() {
Debug.Log("MyMethod is being called");
}
}

So when we enter play mode, at Start, “Start is being called” will be printed out and then “MyMethod is being called” will be printed out.

Keep in mind, if you ever have any sort of player input like they are pressing a key, typically that should always be handled in the Update method, which is called 60 times per second.

Always try to minimize if statements and loops (heavier calculations) in the Update method, as the Update method runs the code 60 times/frames per second.

--

--