UnityAction (Delegate)

2020. 5. 26. 14:47Unity/수업내용

<사용 순서>

 

1. 선언

- 인자를 넘겨주고 싶을땐 UnityAction<T> 로 넘겨받을 인자의 탬플릿을 잡아준다.

- 넘겨줄 인자의 데이터가 있는 위치에서 사용하여, 해당 데이터를 함수에 인자 집어넣듯이 집어넣으면 된다.

 

2. 정의

- 굳이 선언된 클래스가 아닌 다른 클래스(밖)에서도 얼마든지 정의가 가능하다.

- 람다식과 무명 메소드를 적극 사용하면 편하다.

- 인자를 넘겨받아서 사용하고 싶을 땐 무명메소드 부분 ( ) 안에 값을 넣으면 된다.

3. 사용

 

 

<2020-07-29> 추가 예시 - 네트워크 프로그래밍

1. <UIPopupPrompt.cs>

public class UIPopupPrompt : MonoBehaviour
{ 
    public Button btnOk;
    public InputField inputNewMemberName;
    private int id;

    public System.Action<int, string> OnClickOk;
    
    public void Init()
    {
        this.btnOk.onClick.AddListener(() =>
        {
            this.OnClickOk(this.id, this.inputNewMemberName.text);
        });
    }
}

- OnClickOk의 탬플릿 형태를 정해서 선언

- 버튼 이벤트를 통해서 OnClickOk의 함수 진입점을 정하고, 넘길 인자를 결정

 

2. <Test.cs> - Main

public class Test : MonoBehaviour
{
    public UIPopupPrompt uiPopupPrompt;

    void Start()
    {
        this.uiPopupPrompt.Init();
        this.uiPopupPrompt.OnClickOk = (id, newMemberName) =>
        {
            Debug.LogFormat($"{id}, {newMemberName}");

            var req = new Protocols.req_member_put();
            req.membername = newMemberName;

            this.UpdateMemberName(id, req);
        };
    }
}

- OnClickOk 함수의 구체적인 내부 구성은 넘겨받은 인자(사용할 데이터)가 존재하지 않는 타 클래스

- 무명 메소드와 람다식을 활용하여 데이터를 받아 바로 사용하도록 내부 구성을 코딩할 수 있음

 

 

<2020-08-12> 추가 예시 - GPGS 연동

1. <GPGSManager.cs>

public class GPGSManager
{
	private static GPGSManager instance;
    
    public void Init()
    {
        PlayGamesClientConfiguration conf = new PlayGamesClientConfiguration.Builder().Build();

        PlayGamesPlatform.InitializeInstance(conf);
        PlayGamesPlatform.DebugLogEnabled = true;
        PlayGamesPlatform.Activate();
    }
    
	public void GetUserProfile(System.Action<UserProfile> onComplete)
    {
        Debug.Log(Social.localUser.authenticated);
        Debug.LogFormat("userName: {0}, image: {1}", Social.localUser.userName, Social.localUser.image);
        PlayGamesHelperObject.RunCoroutine(LoadImage(() =>
        {
            var profile = new UserProfile(Social.localUser.userName, Social.localUser.image);
            onComplete(profile);
        }));
    }
    private IEnumerator LoadImage(System.Action onComplete)
    {
        Debug.Log("LoadImage");
        yield return new WaitUntil(() => Social.localUser.image != null);
        Debug.Log("image loaded: " + Social.localUser.image);
        onComplete();
    }
    public class UserProfile
    {
        public string userName;
        public Texture2D image;
        public UserProfile(string userName, Texture2D image)
        {
            this.userName = userName;
            this.image = image;
        }
    }
}

 

2. <App.cs> - Main

public class App : MonoBehaviour
{
    public GPGSManager instance;
    public Button btnGetProfile;
    public Image imgProfile;
    public Text txtProfile;
	this.btnGetProfile.onClick.AddListener(() =>
    {
        this.instance.GetUserProfile((profileData) =>
        {
            Debug.LogFormat($"Log//ProfileName : {profileData.userName}, ProfileImage : {profileData.image}");
            Rect rect = new Rect(0, 0, profileData.image.width, profileData.image.height);
            this.imgProfile.sprite = Sprite.Create(profileData.image, rect, new Vector2(0.5f, 0.5f));
            this.txtProfile.text = profileData.userName;
        });
    });
}

- 해석 순서는 다음과 같다.

 1) <App.cs>에서 <GPGSManager.cs>의 메서드인 GetUserProfile()을 호출한다.

 2) GetUserProfile() 안에서 RunCoroutine을 만나고, 코루틴 메서드인 LoadImage()로 넘어간다.

 (* 여기서!! 아래의 이 부분은 LoadImage() 메서드의 콜백을 받은 후 실행될 무명 메서드 부분이다. 순서에 유의하자.)

 var profile = new UserProfile(Social.localUser.userName, Social.localUser.image);
            onComplete(profile);

 3) LoadImage() 메서드 마지막에 OnComplete()를 만나면, GetUserProfile() 메서드 안의 LoadImage의 인자에 해당하는 위치에 있던 무명메서드가 실행된다. (여기서 GPGS 연동을 통해 로그인된 유저의 데이터값을 개발자가 다루기 편한 클래스 형태인 UserProfile Class 형태로 만들어서 저장한다.)

 4) 그 후 방금 LoadImage()에서와 마찬가지로 OnComplete(profile)을 만나고 1)번의 호출부로 돌아간다. 다만 방금 전과의 차이점은, LoadImage()에서는 콜백 메서드만 실행시켰지만 GetUserProfile() 쪽에서는 개발자가 다루기 위한 유저의 profileData를 넘기면서 실행한다는 것이다.

 5) 인자로 넘겨받은 profileData를 이용해서 원하는 기능 구현

 

- 위의 과정에서 콜백 메서드 실행 시 넘겨받는 인자를 가리키는 profileData의 경우, 이미 넘어오는 데이터는 정해져있다. 그리고 넘어오는 데이터를 받아서 일회성으로 쓰는데에만 사용하는 용도이기 때문에 (인지는 정확하진 않다), 해당 데이터의 변수명은 따로 선언해야 한다던가 하는것이 없다. 그냥 본인이 알아보기 편하게 아무렇게나 써도 된다.  

'Unity > 수업내용' 카테고리의 다른 글

Raycast 클릭 처리에서 UI 제외하기  (0) 2020.05.27
HudText  (0) 2020.05.26
Camera Setting  (0) 2020.05.25
Slider 만들기  (0) 2020.05.21
Scroll 만들기  (0) 2020.05.19