[TIL] 10주차 2일 Delegate
오늘은 특강에서 다뤘던 Delegate에 대해서 써보려고 한다.
먼저 Delegate란 무엇일까?
Delegate는 대리자 이다.
구독되어 있는 함수를 대신 실행시키고, 구독시킬 수 있는 함수는 매개변수와 리턴 값이 동일해야한다.
간단하게 말하자면 함수를 변수화 시키는 느낌이며, 하나의 목표를 가진 집단이라고 생각할 수 있다.
기본적인 형식은 다음과 같다.
public delegate void MyTestDelegate();
public delegate void MyDelegate(int a, int b);
void Awake ()
{
MyDelegate cal = new MyDelegate(Plus);
cal += Subtract
cal(1, 2);
}
public void Plus(int a, int b)
{
Debug.Log(a+b);
}
위 코드의 결과는 어떻게 나올까?
정답은 3이다.
cal 델리게이트에 Plus함수가 구독되어 사용되었다. 가장 기본적인 사용법이긴한데
델리게이트에도 파생되는 종류가 있다.
Delegate의 종류
event 형식의 Delegate
OnEvent는 외부에서 실행이 안된다. +=나 = 왼쪽에만 가능 외부에서 구독은 가능하다.
public event MyTestDelegate OnEvent;
public event MyDelegate OnEventInt;
Action 형식의 Delegate
반환값이 없는 Delegate
형식이 지정되어있음 -> public delegate void Action();
public Action action;
public Action<int> actionInt;
Func 형식의 Delegate
Action과 반대로 반환값이 있다.
func<int> = func
func<int, int, int> = funcInt
이 외에도 UnityAction, UnityEvent도 있다.
델리게이트를 가장 간단하게 설명하자면 다음과 같다.
delegate = action(반환x) + func(반환) (event)
실행을 시켜주면 구독되어있는 함수들을 전부 실행한다.
델리게이트에 메서드를 넣고 인보크 하면 델리게이트 안에 있는 메서드가 전부 실행이된다.
그럼 델리게이트는 어떤 상황에 사용할 수 있을까?
delegate void MyDelegate();
MyDelegate = OnDead;
public Button btn;
private void Awake()
{
OnDead += DeadAnim;
OnDead += DeadUI;
OnDead += StopMove;
btn.onClick.AddListener(MinusCount);
}
void DeadAnim()
{
Debug.Log("Dead");
}
void DeadUI()
{
Debug.Log("Active Dead UI");
}
void StopMove()
{
Debug.Log("Player Stop")
}
public void MinusCount()
{
UIManager.instance.Count -= 1;
Debug.Log(UIManager.instance.Count)
if(UIManager.instance.Count.Equals(0))
{
OnDead?.Invoke();
}
}
이 코드는 UI에 버튼을 누를 때마다 숫자가 1씩 내려가게되는데 0이되면 죽는 코드이다.
근데 죽을 때 3가지의 메서드를 아주 간단하게 동시에 실행시킨 모습을 볼 수 있다.
DeadAnim, DeadUI, StopMove 세가지 메서드를 Awake에서 OnDead에 구독시킨 후
만약 Count가 0이 되면 OnDead를 실행시키도록 했다.