Functions with Return Values

Learn how to return values from functions using the return keyword in C#. Understand different return types and variable scope.

return Keyword

A way to return calculated results from a function. Used in games for calculating player health, damage, scores, etc.

public class Player : MonoBehaviour
{
    public int currentHp = 100;
    public int maxHp = 100;
    
    // Function that returns current health percentage
    float GetHealthPercentage()
    {
        return (float)currentHp / maxHp;  // Returns value between 0.0 and 1.0
    }
    
    void Update()
    {
        float healthPercent = GetHealthPercentage();
        Debug.Log("Health: " + (healthPercent * 100) + "%");
    }
}
  • Usage
public class GameManager : MonoBehaviour
{
    // Returns player's current level
    int GetPlayerLevel()
    {
        return 10;  // In reality, returns stored level value
    }
    
    void Start()
    {
        int level = GetPlayerLevel();  // level stores 10
        Debug.Log("Current level: " + level);  // Outputs "Current level: 10"
        
        // Can also use return value directly
        if (GetPlayerLevel() >= 5)
        {
            Debug.Log("Level 5 or above!");
        }
    }
}

Return Types

When creating a function, you must specify what type of value it returns. Games use functions that return various types of values.

public class Player : MonoBehaviour
{
    public int hp = 100;
    public string playerName = "Player";
    public bool isAlive = true;
    
    // Returns int type: health, score, level, etc.
    int GetCurrentHp()
    {
        return hp;
    }
    
    // Returns string type: name, message, etc.
    string GetPlayerName()
    {
        return playerName;
    }
    
    // Returns bool type: status checks, etc.
    bool IsPlayerAlive()
    {
        return hp > 0;  // Returns true if health is greater than 0
    }
    
    // Returns float type: speed, ratio, etc.
    float GetMoveSpeed()
    {
        return 5.5f;
    }
    
    void Start()
    {
        int health = GetCurrentHp();
        string name = GetPlayerName();
        bool alive = IsPlayerAlive();
        
        Debug.Log(name + "'s health: " + health);
        Debug.Log("Alive: " + alive);
    }
}

Using Variables Inside Functions

You can create and use variables inside functions. Useful for storing temporary values during calculations.

public class DamageCalculator : MonoBehaviour
{
    // Function that calculates damage
    int CalculateDamage(int baseDamage, int weaponPower)
    {
        int totalDamage = baseDamage + weaponPower;  // Declare variable inside function
        int criticalBonus = totalDamage / 2;        // Additional calculation
        int finalDamage = totalDamage + criticalBonus;  // Final damage
        
        return finalDamage;  // Return result
    }
    
    void Start()
    {
        int damage = CalculateDamage(10, 5);
        Debug.Log("Final damage: " + damage);
    }
}
  • Variable Scope
    • Variables created inside a function can only be used within that function
    • Cannot be used in other functions
    • Can use variables with the same name in different functions

Game development example:

public class Player : MonoBehaviour
{
    public int baseAttack = 10;
    public int weaponPower = 5;
    
    // Function that calculates attack power
    int GetTotalAttackPower()
    {
        int total = baseAttack + weaponPower;  // Internal variable
        return total;
    }
    
    // Cannot use total variable here (different function)
    void ShowStats()
    {
        // int total = ...;  // Can declare new variable here (different variable)
        Debug.Log("Attack power: " + GetTotalAttackPower());
    }
}

← Back to Table of Contents