C# METHODS, PARAMETERS & RETURN TYPES IN UNITY

Learn how to break large game systems into clean, reusable functions, pass data safely with parameters, and return calculated combat results.

1. Anatomy of a C# Method

A method is a self-contained block of instructions that performs a specific task. Structuring code into small, single-responsibility methods adheres to the DRY (Don't Repeat Yourself) principle.

// Access Modifier + Return Type + Method Name + (Parameters)
public float CalculateDamage(float baseDamage, float armorMultiplier)
{
    float finalDamage = baseDamage * (1f - armorMultiplier);
    return Mathf.Max(1f, finalDamage); // Returns the result back to caller
}

2. Void vs Value-Returning Methods

void (Action Methods)
Performs an action but sends no data back (e.g. void PlayExplosionEffect(), void RespawnPlayer()).
Return Types (Query Methods)
Calculates a value and passes it back (e.g. bool HasEnoughAmmo(int cost), Vector3 GetPredictedTargetPosition()).

3. Parameter Modifiers: Value vs Reference

By default in C#, value types (floats, ints, structs) are passed by copy. Changes made inside the method do not affect the original variable unless you use parameter modifiers:

using UnityEngine;

public class CombatUtility : MonoBehaviour
{
    // 'out' requires the method to assign a value before returning
    public bool TryFindNearestEnemy(Vector3 origin, float radius, out Transform target)
    {
        Collider[] hits = Physics.OverlapSphere(origin, radius);
        foreach (Collider hit in hits)
        {
            if (hit.CompareTag("Enemy"))
            {
                target = hit.transform;
                return true; // Found enemy
            }
        }

        target = null;
        return false; // No enemy found in radius
    }
}

Related C# Guides & Tools

Frequently Asked Questions

Method overloading allows multiple methods to share the exact same name as long as their parameter counts or parameter types differ (e.g. TakeDamage(float amount) vs TakeDamage(float amount, DamageType type)).
No. The C# IL2CPP / JIT compiler performs method inlining automatically for small functions in production builds, eliminating function call overhead while keeping your source code clean and readable.