유니티 C# : Event, delegate

5P2RS5·2023년 8월 14일

일상 Unity

목록 보기
8/9
post-thumbnail

유니티 이벤트 및 델리게이트

📌 주 목적 : 코드가 뒤죽박죽으로 되는 코드의 스파게티화를 방지하기 위함.

델리게이트

정의 : 대리자, 메서드를 담을 수 있는 타입, 함수를 담아준다.
선언 방법 : delegate 반환타입 델리게이트이름(매개변수);
ex) : delegate void ExampleDelegate();

사용 방법 :

ExampleDelegate del = new ExampleDelegate(Hello);
void Hello()
{
	Debug.log("Hello, World");
}

or

ExampleDelegate del = Hello;
del(); // 호출

멀티캐스트

정의 : 여러 개의 메서드를 담을 수 있다는 뜻
메서드 추가 : += 사용
메서드 제거 : -= 사용

예시 :

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript1 : MonoBehaviour
{
    delegate void HelloWorld();

    private HelloWorld call;

    private void Awake()
    {
        call += Hello;
        call += World;
    }

    private void Start()
    {
        call();
    }
    
    void Hello()
    {
        Debug.Log("Hello,");
    }
    
    void World()
    {
        Debug.Log("World!");
    }
}

결과 :

이벤트

정의 : 델리게이트를 이용한 콜백을 좀 더 기능적으로 만들어주는 키워드
이벤트를 사용하면 델리게이트 콜백에서 델리게이트 변수를 넘겨주었던 과정까지 생략할 수 있다.
개념 :
publisher : 실행자를 의미
subscriber : 구독자 실행자의 이벤트에 구독한다.

EventExample 클래스(publisher) :

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;



public class EventExample : MonoBehaviour
{
    public delegate void eventHandler();
    public static event eventHandler hand;

    private void Start()
    {
        hand();
    }
}

HelloWorld 클래스(subscriber) :

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelloWorld : MonoBehaviour
{
    private void Awake()
    {
        EventExample.hand += Hello;
        EventExample.hand += World;
    }

    void Hello()
    {**텍스트**
        Debug.Log("Hello,");
    }
    
    void World()
    {
        Debug.Log("World!");
    }
}

실행 결과 :

⭐️이벤트에 대한 추가

이벤트의 구독자는 자신이 어디에서 호출이 되는지는 모른다.
다만, 자신이 호출되면 그에 맞게 실행은 되어준다.
예시처럼 static 변수를 사용하지 않고 HelloWorld 스크립트파일에 "알잘딱깔센" 변수 할당해서 실행해도 된다.

profile
☀️ Infra_Architecture 🔁 🌔 Game_Dev

0개의 댓글