회원 로그인
정보기억 정보기억에 체크할 경우 다음접속시 아이디와 패스워드를 입력하지 않으셔도 됩니다.
그러나, 개인PC가 아닐 경우 타인이 로그인할 수 있습니다.
PC를 여러사람이 사용하는 공공장소에서는 체크하지 마세요.
소셜네트워크 서비스를 통해서 로그인하시면 별도의 로그인 절차없이 회원서비스를 이용하실 수 있습니다.


최근 게시물

1.노션에서 작성 중

1.노션에서 작성 중

개편하기 전까지 노션에서 작성 중

2024.04.04//read more

2.ChatGPT

2.ChatGPT

OpenAI로 대규모 언어 모델대화형...

2023.03.16//read more

3.노코딩 게임 엔진 - 빌..

3.노코딩 게임 엔진 - 빌..

빌드 지원안드로이드iOS윈도우즈특이사...

2023.03.14//read more

4.(완료) 미접속 회원 정..

4.(완료) 미접속 회원 정..

[완료] 36명의 회원을 정리하였습니...

2023.02.16//read more

5.매뉴얼 플러스 - 전자제..



안정적인 DNS 서비스 DNSEver
DNS Powered by DNSEver.com


Delegate (델리게이트) (with Unity)

푸딩뱃살 | 2015.12.01 10:44 | 조회 6266
C# Delegate (델리게이트)
- 대리인이란 뜻으로 특정 객체의 상태에 따라 통지를 받을 객체를 연결하는 구조를 말한다.

[문법]
1. 델리게이트 선언
public delegate void 델리게이트명(인자);
public static delegate event 델리게이트명 이벤트명;

2. 델리게이트 이벤트 연결
- 이벤트 연결 : 이벤트가 선언된 클래스명.이벤트명 += 이벤트 발생 시 호출되는 메소드
- 이벤트 연결 해제 : 이벤트가 선언된 클래스명.이벤트명 -= 이벤트 발생 시 호출되는 메소드

CDelegate.cs
using UnityEngine;
using System.Collections;

public class GamePlayer
{
    private string palyName = "홍길동";
    // 델리게이트 선언
    public delegate void PlayerDieHandler();
    // 이벤트 선언
    public static event PlayerDieHandler OnPlayerDie;

    // 게임 플레리어가 사망
    public void Die()
    {  
        // 델리게이트를 연결한 몬스터에게 이벤트를 발동시킨다
        GamePlayer.OnPlayerDie();
    }

}

public class Monster
{
    public static int monsterNum = 0;

    public Monster()
    {
        monsterNum++;
        Debug.Log(monsterNum + " 몬스터가 생성됨");

        // 델리게이트 연결함
        GamePlayer.OnPlayerDie += this.OnPlayerDie;

        // 델리게이트 연결 해제
        // GamePlayer.OnPlayDie -= this.OnPlayerDie;
    }

    // 이벤트 발동 메소드
    void OnPlayerDie()
    {
        Debug.Log(monsterNum + " 몬스터는 플레이어가 사망했다고 통지 받음");
    }
}

public class CDelegate : MonoBehaviour
{
    void Start()
    {
        GamePlayer player = new GamePlayer();
        Monster[] monsters = new Monster[5];
        for (int i = 0; i &;t; monsters.Length; i++)
        {
            monsters[i] = new Monster();
        }

        // 플레이어가 사망함 => 통지 발동
        player.Die();
    }
}

CNonDelegateTest.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

// 플레이어 노티 인터페이스
public interface IPlayerNoti
{
    void OnPlayerDie();
}

// 플레이어 통지를 받을 수 있는 몬스터
public class CMonster : IPlayerNoti
{
    int _monsterNum; // 몬스터 번호

    public CMonster(int num)
    {
        _monsterNum = num;
    }

    // 플레이어로 부터 사망을 통지 받을 이벤트 함수
    public void OnPlayerDie()
    {
        Debug.Log(_monsterNum + "번 몬스터가 플레이어의 사망을 통지 받았음.");
    }
}

// 플레이어 통지를 받을 수 있는 NPC
public class CNPC : IPlayerNoti
{
    // 플레이어로 부터 사망을 통지 받을 이벤트 함수
    public void OnPlayerDie()
    {
        Debug.Log("NPC가 플레이어의 사망을 통지 받았음.");
    }
}

// 플레이어 클래스
public class CPlayer
{
    string _name; // 플레이어 이름

    // 플레이어 통지 오브젝트 리스트
    List<IPlayerNoti> _notiObserverList;

    public CPlayer()
    {
        // 플레이어 사망을 통지 받을 몬스터 리스트 생성
        _notiObserverList = new List<IPlayerNoti>();
    }

    // 통지 인터페이스를 구현한 오브젝트들을 등록함
    public void RegisterNotiMonster(IPlayerNoti observer)
    {
        _notiObserverList.Add(observer);
    }

    // 몬스터들에게 플레이어의 사망을 통지함
    public void PlayerDieNoti()
    {
        foreach (IPlayerNoti observer in _notiObserverList)
        {
            observer.OnPlayerDie();
        }
    }

    // 플레이어가 사망함
    public void Die()
    {
        Debug.Log(_name + " 플레이어가 사망함... ");
        PlayerDieNoti(); // 몬스터들에게 플레이어 사망을 알림
    }
}

public class CNonDelegateTest : MonoBehaviour
{
    void Start()
    {
        // 플레이어를 생성함
        CPlayer player = new CPlayer();
        // 몬스터 10마리의 참조 배열을 생성함
        CMonster[] monsters = new CMonster[10];
        // NPC를 생성함
        CNPC npc = new CNPC();

        // 몬스터 10마리를 생성하고 플레이어 통지를 받도록 등록함
        for (int i = 0; i < 10; i++)
        {
            monsters[i] = new CMonster(i);
            player.RegisterNotiMonster(monsters[i]);
        }

        // NPC에게 플레이어 통지를 받도록 등록함
        player.RegisterNotiMonster(npc);

        // 플레이어가 사망함
        player.Die();
    }
}

간단 예제
using UnityEngine;
using System.Collections;

/*
delegate 복습

-함수 포인트(주소) 값
*/

public class DelegateTest : MonoBehaviour {
    
    // class Cale
    // enum Cale

    // 특정 변수에 함수의 주소값 보관 목적(선언)
    // System.Action<int a, int b>; 와 같음
    delegate void Calc(int a, int b); 

    void Add(int a, int b)
    {
        int result = a + b;
        print(result);
    }

    void Mul(int a, int b)
    {
        int result = a * b;
        print(result);
    }

    void Start () {
        /*
        Calc calc = Add;
        calc(10, 30);
        calc = Mul;
        calc(10, 30);
        */
        /* 결과
        40
        300
        */

        // 위 명령과 똑같음
        Calc calc = Add;
        calc += Mul;  // calc 주소에 함수 여러개 등록 사용(현재 Add와 Mul가 추가됨)
        calc(10, 30);
        /* 결과
        40
        300
        */

        calc -= Mul;  // 주소에 함수를 뺌
        calc(10, 30);
        /* 결과
        40
        */

        // 델리게이트 배열에 함수 등록
        Calc[] cals = new Calc[2];
        cals[0] = Add;
        cals[1] = Mul;
        
        // for문일 때
        for (int i = 0; i < cals.Length; i++)
        {
            cals[i](10, 30);
            print(cals[i]);
        }
        /*결과
        40
        DelegateTest+Calc
        300
        */

        // foreach문일 때
        foreach(Calc c in cals)
        {
            c(10, 30);
            print(c);
        }
        /*결과
        40
        DelegateTest+Calc
        300
        */
    }
}
285개(6/15페이지)
프로그래밍
번호 제목 글쓴이 조회 날짜
185 [PHP] 회원가입 + 로그인 스크립트 (with Unity) [2+1] 푸딩뱃살 12240 2015.12.06 17:31
184 [C#] C# 추천 서적 푸딩뱃살 1320 2015.12.06 17:16
183 [C/C++] C++ 참고 사이트 푸딩뱃살 1181 2015.12.04 16:13
182 [PHP] 클래스 푸딩뱃살 3580 2015.12.04 14:40
181 [PHP] CodeIgniter(코드이그나이트) 첨부파일 푸딩뱃살 2931 2015.12.04 14:40
>> [C#] Delegate (델리게이트) (with Unity) 푸딩뱃살 6267 2015.12.01 10:44
179 [PHP] php 함수 푸딩뱃살 2219 2015.11.30 15:33
178 [PHP] Dictionary (딕셔너리) 첨부파일 푸딩뱃살 2868 2015.11.27 12:37
177 [PHP] 배열 푸딩뱃살 2170 2015.11.27 12:37
176 [PHP] 변수 선언 / 산술 연산 푸딩뱃살 2182 2015.11.27 11:14
175 [C#] Dictionary (딕셔너리) (with Unity) 첨부파일 [3+3] 푸딩뱃살 14483 2015.11.25 10:29
174 [C#] List (리스트) (with Unity) 첨부파일 푸딩뱃살 12087 2015.11.24 10:22
173 [C#] Generic (제네릭) (with Unity) 푸딩뱃살 4888 2015.11.22 12:32
172 [C/C++] Templete (템플릿) 푸딩뱃살 2045 2015.11.22 12:15
171 [C#] 키보드 입력 푸딩뱃살 3568 2015.11.21 18:00
170 [C#] 예외와 예외 처리 푸딩뱃살 4124 2015.11.21 17:39
169 [C#] Struct (구조체) (with Unity) 푸딩뱃살 5123 2015.11.18 22:08
168 [C#] Property (프로퍼티) (with Unity) 푸딩뱃살 2443 2015.11.18 10:50
167 [C#] interface (인터페이스) (with Unity) 첨부파일 푸딩뱃살 3306 2015.11.15 17:32
166 [C#] 스트림 (stream) - 문자, 바이너리 읽기/쓰기 푸딩뱃살 12780 2015.11.14 18:24