Methods

What are methods in C#?

Methods–also known as functions–are blocks of code that perform specific tasks. They allow you to group behavior, re-use logic, and organize your code.

In Unity, methods are everywhere–Start(), Update(), and OnTriggerEnter() are methods. Unity automatically calls these built-in methods, but you can (and should) define your own too.

More on Methods

A method is a named block of code that performs a specific task. Think of it like a mini machine or tool inside your program: once you build it, you can use it over and over again. Instead of writing the same lines of code again and again, you write them once inside a method and then call that method whenever you need it.

In everyday life, a method is like a recipe. If you want to make a sandwich, you don’t rewrite the instructions every time — you just follow the steps you already know. In programming, methods are your way of writing down those steps so your program (and you) can use them later.

Here’s a simple example: imagine you’re writing a game, and your player needs to take damage when hit by an enemy. Instead of copying the same “subtract health” logic every time the player might get hit, you can write a method called TakeDamage, and just call that method whenever damage needs to be applied.

A method can also accept input — these are called parameters. Using our real-world example again: if a recipe lets you choose the number of sandwiches you want to make, that number becomes a parameter — an input to the method. In code, parameters are like variables you pass into the method so it can do something useful with them.

Methods can also give you something back — this is called a return value. It’s like asking a calculator to add two numbers for you. You give it two inputs, and it returns the result. In code, a method might return a number, a message, a game object, or anything else your program needs.

Every method in C# starts with a definition that tells the computer what kind of thing it returns (or if it returns nothing), what it’s called, and what inputs it expects. Then inside the method, you write the steps — the logic that gets executed when the method is used. When the method is called, that logic runs line by line, just like a little program inside your program.

What makes methods powerful is that they allow you to simplify and organize your code. Instead of cramming dozens of lines of logic into Unity’s Update() function, you break it apart. You might have one method that handles movement, another for jumping, another for attacking. Then, inside Update(), you just call those smaller methods. It’s like giving each part of your game its own job — making it easier to fix, understand, and reuse.

As your projects grow, methods help keep things from spiraling out of control. They help you think clearly about what your code is doing. They let you re-use logic in multiple places, keep track of how and why something works, and make your scripts much easier to read. Whether you’re building a health system, triggering dialogue, calculating knockback, or spawning enemies, you’ll be using methods everywhere.

Learning to use methods is one of the first steps to thinking like a programmer. Once you understand them, you stop seeing code as a list of instructions — and start seeing it as a set of organized tools that work together. Each method becomes a sentence in your game’s language. And just like in real language, when you can structure your thoughts into clear, well-formed sentences, you can express anything.


Why Use Methods?

  • Break code into manageable chunks
  • Avoid repetitive code
  • Make code easier to test, debug, and understand
  • Build modular, reusable systems
  • Clean up Update() and other loops by offloading logic

Basic Method Structure

C#
returnType MethodName(parameters)
{
    // Your code here
}



MethodName(); //Calling the method


Simple Examples


1. Void Method (does a task, doesn’t return anything)
C#
void SayHello()
{
    Debug.Log("Hello, player!");
}

2. Method with Input Parameters
C#
void Greet(string name)
{
    Debug.Log("Hello, " + name);
}

3. Method that Returns a Value
C#
int Add(int a, int b)
{
    return a + b;
}

Calling a Method


You must call (or invoke) a method for it to run. Let’s call our example methods.

C#
void Start()
{
    SayHello();          // Calls method above
    
    Greet("Zombies!");   // Outputs: Hello, Zombies!
    
    int result = Add(3, 4);
    Debug.Log(result);   // Outputs: 7
}


How Methods Interact with Other Code

Unity relies on method callbacks and your own custom methods to make the game work.

  • Variables can be passed into methods as parameteres
  • Methods can access public/private variables inside the same script
  • Return values let you use results from one method inside another
  • Other scripts can call your method if it’s public
  • Methods can only access variables within their scope
  • Use public to make methods accessible to other scripts

Game Dev Examples — From Simple to Intermediate

Example 1: Flash Message

C#
void ShowMessage(string text)
{
    Debug.Log(text);
}

Use Case: Popup messages, console logging, dialogue triggers

Example 2: Take Damage (GameObject Health)

C#
public void TakeDamage(int amount)
{
    currentHealth -= amount;
    if (currentHealth <= 0)
    {
        Die();
    }
}

Use Case: Enemy or Player health system

Example 3: Spawn an Enemy at a Random Location

C#
public GameObject enemyPrefab;
public Transform[] spawnPoints;

void SpawnEnemy()
{
    int index = Random.Range(0, spawnPoints.Length);
    Instantiate(enemyPrefab, spawnPoints[index].position, Quaternion.identity);
}

Use Case: Enemy waves, survival mode, spawn zones

Example 4: Calculate Knockback Force

C#
Vector3 CalculateKnockback(Vector3 attackerPosition, float force)
{
    Vector3 direction = (transform.position - attackerPosition).normalized;
    return direction * force;
}

Use Case: Combat feedback, physics-based reactions, crowd control

Example 5: Equip Weapon Logic

C#
public void EquipWeapon(ItemData weapon)
{
    currentWeapon = weapon;
    UpdateWeaponModel();
    UpdateUI();
}

Use Case: Inventory systems, weapon switching, multiplayer loadouts

Example 6: Combo Counter Reset (Using Coroutines)

C#
void ResetCombo()
{
    comboCounter = 0;
    comboTimer = maxComboTime;
}

Use Case: Melee combos, skill chains, precision-based fighting

Leave a Comment

Your email address will not be published. Required fields are marked *