카테고리 없음

델리게이트 Action 과 Event Action 설명

이더23 2024. 10. 24. 14:16

Action 사용

Action은 반환값이 없고, 매개변수를 가질 수 있는 델리게이트이다.

Action만을 사용해서 이벤트를 걸어주면 해당 Action에 Invoke를 사용할 수 있는 위치가 넓어지며, 어느 곳에서든 호출할 수 있다.

그렇게 하기 싫다면 event을 함께 사용하여 정의하면, 예를 들어 public event Action OnScoreChanged;와 같이 코드를 작성하면, 해당 Action을 선언한 클래스를 제외하고는 어디서든 Invoke를 사용할 수 없게 된다. 즉, event를 사용함으로써 외부에서의 직접 호출을 방지하고, 이벤트가 발생했을 때 의도된 동작만 수행하도록 할 수 있다. 이는 코드의 안정성과 가독성을 높이는 데 도움이 된다.

 

Action 사용 예시

public class ScoreButton : MonoBehaviour
{
    public Button scoreButton;
    public int score;
    public Action<int> OnScoreChanged;

    private void Awake()
    {
       scoreButton = GetComponent<Button>();
       scoreButton.onClick.AddListener(PointUp);
    }

    public void PointUp()
    {
       score += 1;
       OnScoreChanged?.Invoke(score);
    }
}

이벤트 발생하는 곳

public class ScoreText : MonoBehaviour
{
    public ScoreButton scoreButton;
    private TextMeshProUGUI scoreText;

    void Start()
    {
        scoreText = GetComponent<TextMeshProUGUI>();
        scoreButton.OnScoreChanged += RefreshUI;
    }

    // Update is called once per frame
    public void RefreshUI(int score)
    {
        scoreText.text = score.ToString();
    }
}

 

참고

Action만을 사용하면 이벤트가 발생하는 곳에서도 이렇게 Invoke를 사용할 수 있다.

void Start()
{
    scoreText = GetComponent<TextMeshProUGUI>();
    scoreButton.OnScoreChanged += RefreshUI;
    scoreButton.OnScoreChanged?.Invoke(1);
}