반환값이 있는 함수

C#에서 return 키워드를 사용하여 함수에서 값을 반환하는 방법을 학습합니다. 다양한 반환 타입과 변수 스코프를 이해합니다.

return 키워드

함수(function)에서 계산한 결과를 돌려주는 방법입니다. 게임에서 플레이어의 체력 계산, 데미지 계산, 점수 계산 등에 사용합니다.

public class Player : MonoBehaviour
{
    public int currentHp = 100;
    public int maxHp = 100;
    
    // 현재 체력 비율을 반환하는 함수
    float GetHealthPercentage()
    {
        return (float)currentHp / maxHp;  // 0.0 ~ 1.0 사이의 값 반환
    }
    
    void Update()
    {
        float healthPercent = GetHealthPercentage();
        Debug.Log("체력: " + (healthPercent * 100) + "%");
    }
}
  • 사용 방법
public class GameManager : MonoBehaviour
{
    // 플레이어의 현재 레벨을 반환
    int GetPlayerLevel()
    {
        return 10;  // 실제로는 저장된 레벨 값을 반환
    }
    
    void Start()
    {
        int level = GetPlayerLevel();  // level에 10이 저장됨
        Debug.Log("현재 레벨: " + level);  // "현재 레벨: 10" 출력
        
        // 반환값을 바로 사용할 수도 있음
        if (GetPlayerLevel() >= 5)
        {
            Debug.Log("레벨 5 이상입니다!");
        }
    }
}

반환(return) 타입(type)

함수(function)를 만들 때 어떤 타입(type)의 값을 반환(return)할지 정해야 합니다. 게임에서는 다양한 타입(type)의 값을 반환(return)하는 함수(function)를 사용합니다.

public class Player : MonoBehaviour
{
    public int hp = 100;
    public string playerName = "플레이어";
    public bool isAlive = true;
    
    // int 타입 반환: 체력, 점수, 레벨 등
    int GetCurrentHp()
    {
        return hp;
    }
    
    // string 타입 반환: 이름, 메시지 등
    string GetPlayerName()
    {
        return playerName;
    }
    
    // bool 타입 반환: 상태 확인 등
    bool IsPlayerAlive()
    {
        return hp > 0;  // 체력이 0보다 크면 true
    }
    
    // float 타입 반환: 속도, 비율 등
    float GetMoveSpeed()
    {
        return 5.5f;
    }
    
    void Start()
    {
        int health = GetCurrentHp();
        string name = GetPlayerName();
        bool alive = IsPlayerAlive();
        
        Debug.Log(name + "의 체력: " + health);
        Debug.Log("생존 여부: " + alive);
    }
}

함수(function) 내부에서 변수(variable) 사용

함수(function) 안에서도 변수(variable)를 만들고 사용할 수 있습니다. 계산 과정에서 임시로 값을 저장할 때 유용합니다.

public class DamageCalculator : MonoBehaviour
{
    // 데미지를 계산하는 함수
    int CalculateDamage(int baseDamage, int weaponPower)
    {
        int totalDamage = baseDamage + weaponPower;  // 함수 안에서 변수 선언
        int criticalBonus = totalDamage / 2;        // 추가 계산
        int finalDamage = totalDamage + criticalBonus;  // 최종 데미지
        
        return finalDamage;  // 결과 반환
    }
    
    void Start()
    {
        int damage = CalculateDamage(10, 5);
        Debug.Log("최종 데미지: " + damage);
    }
}
  • 변수(variable)의 범위 (스코프(scope))
    • 함수(function) 안에서 만든 변수(variable)는 그 함수(function) 안에서만 사용 가능
    • 다른 함수(function)에서는 사용할 수 없음
    • 같은 이름의 변수(variable)를 다른 함수(function)에서 사용해도 괜찮음

게임 개발 예시:

public class Player : MonoBehaviour
{
    public int baseAttack = 10;
    public int weaponPower = 5;
    
    // 공격력을 계산하는 함수
    int GetTotalAttackPower()
    {
        int total = baseAttack + weaponPower;  // 함수 내부 변수
        return total;
    }
    
    // 다른 함수에서는 total 변수를 사용할 수 없음
    void ShowStats()
    {
        // int total = ...;  // 여기서 새로 선언 가능 (다른 변수)
        Debug.Log("공격력: " + GetTotalAttackPower());
    }
}

← 목차로 돌아가기