클래스의 생성자 (Constructor)

C#의 생성자를 학습합니다. 객체를 초기화하고 생성자 오버로딩을 사용하는 방법을 이해합니다.

생성자(constructor)란?

생성자(constructor)클래스(class)의 인스턴스(객체(object))를 만들 때 자동으로 실행되는 특별한 함수(function)입니다. 객체(object)를 초기화하는 역할을 합니다.

기본 생성자(constructor)

매개변수(variable)(parameter)가 없는 생성자(constructor)입니다. 클래스(class)에 생성자(constructor)를 작성하지 않으면 자동으로 생성됩니다.

기본 생성자(constructor) 예시

public class Weapon
{
    public string name;
    public int damage;
    
    // 기본 생성자
    public Weapon()
    {
        name = "Unknown";
        damage = 10;
    }
}

// 사용
Weapon weapon = new Weapon();  // 기본 생성자 호출
// weapon.name = "Unknown", weapon.damage = 10

매개변수(variable)(parameter)가 있는 생성자(constructor)

생성 시 값을 전달하여 초기화할 수 있습니다.

매개변수(variable)(parameter) 생성자(constructor) 예시

public class Weapon
{
    public string name;
    public int damage;
    
    // 매개변수가 있는 생성자
    public Weapon(string name, int damage)
    {
        this.name = name;      // this는 현재 객체를 의미
        this.damage = damage;
    }
}

// 사용
Weapon sword = new Weapon("검", 50);
// sword.name = "검", sword.damage = 50

this 키워드

  • this는 현재 객체(object)를 가리킵니다
  • 매개변수(variable)(parameter) 이름과 변수(variable) 이름이 같을 때 구분하기 위해 사용
public Weapon(string name, int damage)
{
    this.name = name;        // this.name = 클래스의 변수
    this.damage = damage;    // name = 매개변수
}

여러 생성자 (Constructor Overloading)

같은 클래스(class)여러 개의 생성자(constructor)를 만들 수 있습니다. 매개변수(variable)(parameter)의 개수나 타입(type)이 달라야 합니다.

생성자(constructor) 오버로딩(overloading) 예시

public class Weapon
{
    public string name;
    public int damage;
    
    // 기본 생성자
    public Weapon()
    {
        name = "Unknown";
        damage = 10;
    }
    
    // 매개변수가 있는 생성자
    public Weapon(string name, int damage)
    {
        this.name = name;
        this.damage = damage;
    }
    
    // 이름만 받는 생성자
    public Weapon(string name)
    {
        this.name = name;
        this.damage = 20;  // 기본 데미지
    }
}

// 사용
Weapon weapon1 = new Weapon();              // 기본 생성자
Weapon weapon2 = new Weapon("검", 50);      // 매개변수 생성자
Weapon weapon3 = new Weapon("방패");        // 이름만 받는 생성자

Unity MonoBehaviour와 생성자(constructor)

Unity의 MonoBehaviour를 상속(inheritance)받은 클래스(class)에서는 생성자(constructor)를 사용할 때 주의가 필요합니다.

주의사항

public class script1123_04 : MonoBehaviour
{
    public Weapon weapon;
    
    // MonoBehaviour에서는 생성자 사용을 권장하지 않음
    // Unity의 생명주기 함수(Awake, Start)를 사용하는 것이 좋음
}

이유: Unity는 객체(object)를 생성하는 방식을 제어하므로, 생성자(constructor)보다는 Awake()Start()를 사용하는 것이 안전합니다.

Unity 함수(function) 실행 순서

Unity는 스크립트가 실행될 때 특정 순서로 함수(function)를 호출합니다.

실행 순서

  1. Awake() - 객체(object)가 생성될 때 (생성자(constructor) 직후)
  2. OnEnable() - 객체(object)가 활성화될 때
  3. Start() - 첫 프레임 전에 한 번만
  4. Update() - 매 프레임마다
  5. LateUpdate() - Update 이후
  6. OnDisable() - 객체(object)가 비활성화될 때
  7. OnDestroy() - 객체(object)가 파괴될 때

자세한 정보

Unity 공식 문서: 실행 순서

예시

public class Player : MonoBehaviour
{
    void Awake()
    {
        Debug.Log("1. Awake 실행");
    }
    
    void Start()
    {
        Debug.Log("2. Start 실행");
    }
    
    void Update()
    {
        Debug.Log("3. Update 실행 (매 프레임)");
    }
}

생성자(constructor) 체이닝

한 생성자(constructor)에서 다른 생성자(constructor)를 호출할 수 있습니다.

public class Weapon
{
    public string name;
    public int damage;
    
    // 기본 생성자
    public Weapon() : this("Unknown", 10)
    {
        // 위의 생성자를 호출하여 초기화
    }
    
    // 매개변수 생성자
    public Weapon(string name, int damage)
    {
        this.name = name;
        this.damage = damage;
    }
}

실전 활용 예시

예시 1: 무기 클래스(class)

public class Weapon
{
    public string name;
    public int damage;
    
    // 기본 생성자
    public Weapon()
    {
        name = "Unknown";
        damage = 10;
    }
    
    // 매개변수 생성자
    public Weapon(string name, int damage)
    {
        this.name = name;
        this.damage = damage;
    }
}

// 사용
Weapon sword = new Weapon("검", 50);
Weapon shield = new Weapon("방패", 20);
Weapon defaultWeapon = new Weapon();  // 기본값 사용

예시 2: 플레이어 클래스(class)

public class Player
{
    public string name;
    public int level;
    public int hp;
    
    public Player()
    {
        name = "Player";
        level = 1;
        hp = 100;
    }
    
    public Player(string name, int level)
    {
        this.name = name;
        this.level = level;
        this.hp = 100;  // 기본 체력
    }
}

생성자(constructor) vs Unity 생명주기

방법 사용 시기 특징
생성자(constructor) 일반 클래스(class) 객체(object) 생성 시 초기화
Awake() MonoBehaviour Unity 객체(object) 초기화
Start() MonoBehaviour 첫 프레임 전 초기화

주의사항

  1. MonoBehaviour에서는 생성자(constructor) 사용 지양: Unity의 생명주기를 사용하는 것이 안전
  2. 생성자(constructor) 이름은 클래스(class) 이름과 동일해야 함
  3. 반환(return) 타입(type)이 없음 (void도 아님)
  4. 여러 생성자(constructor)는 매개변수(variable)(parameter)가 달라야 함

← 목차로 돌아가기