Unity/유니티 개발
[유니티 개발] 동적으로 버튼 이벤트 할당
도이(doi)
2022. 6. 28. 15:42
728x90
개발 진행 과정 중에 동적으로 버튼 이벤트를 할당해주는 경우가 생겼다.
스크립트로 동적으로 instance하는 캐릭터가 가지고 있는 스크립트와 버튼이 연동되기 위해서 필요함.
동적 버튼 이벤트 할당의 장점은 일일히 drag&drop 방식을 통해서 이벤트를 연동해줄 필요가 없다는 것이다.
drag&drop 방식의 이벤트 생성의 문제는 함수의 이름이 바뀔 때 등 특정한 경우에 이벤트의 연결이 끊긴다는 것이다.
동적 버튼 이벤트 할당의 방법은 간단한다.
아래와 같이 스크립트를 작성한 후에 button이 있는 gameobject에 component로 추가해준다.
using UnityEngine;
using UnityEngine.UI;
public class ButtonEventex : MonoBehaviour
{
private Button button;
private void Start()
{
button = GetComponent<Button>(); //버튼 component 가져오기
button.onClick.AddListener((event1)); //인자가 없을 때 함수 호출
button.onClick.AddListener(() => event2(5)); //인자가 있을 때 람다식 사용
}
private void event1()
{
Debug.Log("this is a event1.");
}
private void event2(int arg)
{
Debug.Log($"this is a evnet2 arg {arg}");
}
}
728x90
반응형