본문 바로가기

프로그래밍/Unity 문법

Unity get / set

이번시간에는 Unity에서 사용하는 get과 set에 대해 이해하고 활용하는 법을 알아보겠다.

 

 

 

▶ 정의

 

Unity에서 get/set은 속성(Propertices) 기능을 말한다. 변수의 값을 읽거나 쓸 때 직접 필드를 건드리지 않고, 안전하게 접근하게 해주는 기능이 있다.

 

private int health; // 실제 데이터를 저장하는 필드

public int Health
{
    get { return health; }   // 외부에서 값을 읽을 때 실행
    set { health = value; }  // 외부에서 값을 쓸 때 실행
}

 

private int health: 실제 데이터 저장용 변수

 public int Health: 외부에서 접근할 수 있는 속성

get: 값을 가져갈 때 실행

set: 값을 설정할 때 실행 (value는 전달된 값)

 

 

# 사용 예시

public class Player : MonoBehaviour
{
    private int health = 100;

    public int Health
    {
        get { return health; }
        set 
        {
            health = Mathf.Clamp(value, 0, 100); // 0~100으로 제한
            Debug.Log("Health set to " + health);
        }
    }

    void Start()
    {
        Health = 150; // set 실행, 100으로 제한됨
        Debug.Log(Health); // get 실행, 100 출력
    }
}

 

 

▶ 활용법

 

1. 값 제한

public float Speed { get; set; } = 5f;

 

2. 읽기 전용

// 외부에서는 읽기만 가능, 내부에서만 set 가능
public int Level { get; private set; } = 1;

 

3. 값 변경 시 이벤트 호출

private int score;
public int Score
{
    get => score;
    set
    {
        score = value;
        OnScoreChanged?.Invoke(score); // 값 변경 시 이벤트 호출
    }
}

public event Action<int> OnScoreChanged;

'프로그래밍 > Unity 문법' 카테고리의 다른 글

Unity 스크립트 기본 클래스 정리  (0) 2025.09.12