매서드를 변수처럼 사용할 수 있게 해주는 유용한 친구
델리게이트 (Delegate)는 “대리자”라는 뜻으로 그 이름에서 알 수 있듯이,
매서드를 변수처럼 사용할 수 있도록 해준다.
만약 매서드를 여러개 동시에 실행 시키고 싶을 때 델리게이트를 사용한다.
델리게이트를 선언하는 방법은 아래와 같다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Delegate_Ex : Monobehavior
{
// 한정자(public, private..) delegate 반환형식(int, void..) 이름 (매개 변수)
public delegate void MyDelegate();
MyDelegate myDelegate;
}
델리게이트는 선언된 클래스 내에서만 사용 가능하다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Delegate_Ex : MonoBehaviour
{
public delegate void MyDelegate();
MyDelegate myDelegate;
private void Start()
{
myDelegate = PrintMyName;
myDelegate();
}
private void PrintMyName()
{
Debug.Log("박현민");
}
// 결과: 박현민
}
또한 델리게이트는 하나의 함수만이 아니라 여러 함수를 추가해서 사용할 수 있다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Delegate_Ex : MonoBehaviour
{
public delegate void MyDelegate();
MyDelegate myDelegate;
private void Start()
{
myDelegate += PrintMyName;
myDelegate += PrintMyAge;
myDelegate += PrintObjectName;
myDelegate();
}
private void PrintMyName()
{
Debug.Log("박현민");
}
private void PrintMyAge()
{
Debug.Log("17세");
}
private void PrintObjectName()
{
Debug.Log(gameobject.name);
}
// 결과: 박현민
// 17세
// cube
}
+= 연산자를 활용해서 추가를 할 수 있다.
추가할 때는 += , 제거할 때에는 -= 활용하여 제거할 수 있다.
이벤트나 함수를 등록하고 실행할 수 있게 해주는 역할이기에,
코드의 흐름을 더 간결하고, 명확하게 만들어 줄 수있다.
이벤트를 처리하는데 유용하다. 예를 들어 플레이어가 점프하거나 공격하는 상황에서 다양한 스크립트가 구독하고 반응하게 할 수 있다.
매서드를 파라미터로 전달하거나, 런타임 중에 동적으로 변경할 수 있어, 코드의 유연성을 높힐 수 있다.