jae_coding

[유니티로 배우는 C#] 델리게이트 본문

C#

[유니티로 배우는 C#] 델리게이트

재코딩 2022. 7. 19. 11:44
반응형

델리게이트

여러개의 함수를 한번에 사용하기 위함

 

이전 코드

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

public class Unity_lecture : MonoBehaviour
{
    
    int power;
    int defence;

    public void SetPower(int value){
        power += value;
        print("power의 값이" + value + "만큼 증가하였습니다. 총 power의 값이 " + power + "입니다.");
    }

    public void SetDefence(int value){
        defence += value;
        print("defence의 값이" + value + "만큼 증가하였습니다. 총 defence의 값이 " + defence + "입니다.");
    }

    void Start()
    {
        SetPower(5);
        SetDefence(5);
    }

}

 

델리게이트 사용 코드

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

public class Unity_lecture : MonoBehaviour
{
    public delegate void ChainFunction(int value);
    ChainFunction chain;
    int power;
    int defence;

    public void SetPower(int value){
        power += value;
        print("power의 값이" + value + "만큼 증가하였습니다. 총 power의 값이 " + power + "입니다.");
    }

    public void SetDefence(int value){
        defence += value;
        print("defence의 값이" + value + "만큼 증가하였습니다. 총 defence의 값이 " + defence + "입니다.");
    }

    void Start()
    {
        // chain에 함수 추가하기
        chain += SetPower;
        chain += SetDefence;
        if (chain != null){
            chain(5);
        }

        // chain에 함수 제거하기
        chain -= SetPower;
        if (chain != null){
            chain(5);
        }

    }

}

 

이벤트

델리게이트와 달리 다른 모든 클레스에 대해서 한번에 함수를 추가하고 호출할 수 있다.

 

하위 클레스

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

public class Unity_lecture : MonoBehaviour
{
    public delegate void ChainFunction(int value);
    public static event ChainFunction Onstart;
    int power;
    int defence;

    public void SetPower(int value){
        power += value;
        print("power의 값이" + value + "만큼 증가하였습니다. 총 power의 값이 " + power + "입니다.");
    }

    public void SetDefence(int value){
        defence += value;
        print("defence의 값이" + value + "만큼 증가하였습니다. 총 defence의 값이 " + defence + "입니다.");
    }

    void Start()
    {
        Onstart += SetPower;
        Onstart += SetDefence;
    }

    // 게임이 꺼지거나 객체가 비활성화 될 때
    private void OnDisable()
    {
        Onstart(5);
    }

}

상위 클레스

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



public class Unity_lecture2 : MonoBehaviour
{
    void Start(){
        Unity_lecture.Onstart += Abc;
    }

    public void Abc(int value){
        print(value + "의 값이 증가했습니다");
    }

}

위 상태로 시작이 된다면, 3개의 함수가 모두 호출이 된다고 생각하면된다.

델리게이트는 한개의 클레스만 관리 감독이 가능하지만 이벤트를 사용한다면 상위 클레스도 연결을 하여 관리할 수 있다는 장점을 지니고 있다.

 

강의자료: 케이디 유튜브

반응형
Comments