🎮 Unity 개발/C#

Method 메소드 - void 메소드이름() {}

gameuiux 2023. 9. 1. 06:37
728x90
반응형

Method 메소드

메소드 - 어떤 코드가 실행되는 전체 영역 (void Start, void Update 등)

void 메소드이름() {}

 

쓰는 이유
하나의 영역 내에서 코드를 계속 작성하면 보기 힘듦
비슷한 동작 하는 코드 비슷하게 호출하는 식으로 사용


void - 아무것도 없다 비어있다
메소드이름 - 대문자로 시작하는 영어 단어 조합

 

 

코드

public class _13_Method : MonoBehaviour
{
    void StartGame() {
        Debug.Log("Game Start");
    }

    void EnemyTakeDamage(string name){
        Debug.Log(name + " takes damage.");
    }

    void PlayerTakeDamage(string name, int hp, int damage) {
        hp -= damage;
        Debug.Log(name + " takes damage " + damage); // Lion takes damage 10
        Debug.Log(name + " HP : " + hp); // Lion HP : 90
    }

    int BossTakeDamage(int hp, int damage) {
        hp -= damage;
        Debug.Log("Boss takes damage " + damage);
        return hp;

    }

    string GetPlayerName(){ // string int float 자료형 뭘 써도 상관은 없는데 return 뒤에 들어오는 값이랑 타입이 일치해야 함
        return "Lion"; // 호출한 쪽으로 반환 string playerName
    }


    // Start is called before the first frame update
    void Start()
    {
        StartGame(); // StartGame이라는 메소드를 호출
        EnemyTakeDamage("Enemy1");
        EnemyTakeDamage("Enemy2");
        Debug.Log("--------------------");

        string playerName = GetPlayerName();
        Debug.Log("Player : " + playerName);
        Debug.Log("--------------------");

        PlayerTakeDamage(playerName, 100, 10); // name, hp, damage
        Debug.Log("--------------------");

        int hp = BossTakeDamage(1000, 50); // hp, damage
        Debug.Log("Boss HP : " + hp);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

결과

 

순서대로

기본 메소드 (전달값 반환값 아무것도 없는 메소드)
전달 값 하나만 있는 메소드
반환 값이 있는 메소드
전달 값 여러 개 있는 메소드
전달 값 여러 개 + 반환 값이 있는 메소드 결과 출력

 

728x90
반응형