Delegate
Delegate μμμ΄λ μ 체 μμ μ€ μΌλΆλ₯Ό λκ΅°κ°λ₯Ό λμ ν΄ ν¨μ¨μ μΌλ‘ μ²λ¦¬νλ ννλ₯Ό λ§νλ€.
λ λ€λ₯Έ ννμ μμμΌλ‘ C# μ λλ¦κ³Ό Action λλ Action<T>λ₯Ό μ¬μ©νλ λ°©μμ΄ μλ€.
μμμ μ¬μ©νλ μ£Όμν λ κ°μ ν¨ν΄μ μ€μ κ°λ₯λ©μλ(Configurable method)ν¨ν΄κ³Ό
μμ(delegation) ν¨ν΄μ΄λ€.
1. μ€μ κ°λ₯ λ©μλ ν¨ν΄
μΌμ΄λ ν¨μμ μΌλΆλ₯Ό λ€λ₯Έ λ©μλλ‘ μ λ¬ν΄ μμ μ μλ£νλλ° μ¬μ©νλ ν¨ν΄μ΄λ€.
μ΄ ν¨ν΄μ κ³ μ ν λ°©μμ κ°μ§ κ°λ³ μ½λκ° κ³΅ν΅λ μμ μ μνν λ μ¬μ©νλ€.
μλ₯Ό λ€λ©΄ κ±·κΈ°, λ°κΈ°, νμ λ±μ΄ μ΄μ ν΄λΉνλ€.
μ΄ λͺ¨λ μμ μ μΊλ¦ν°μ κΈ°λ³Έ νμκ° λ μ μλ€.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeleTest : MonoBehaviour
{
//μμ λ©μλ μκ·Έλμ² μ μ
delegate void RobotAction();
//μμμ μν νλΌμ΄λΉ μμ±
RobotAction myRobotAction;
private void Start()
{
//μμμ μν κΈ°λ³Έ λ©μλ μ€μ
myRobotAction = RobotWalk;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.W)) myRobotAction = RobotWalk;//μμ λ©μλλ₯Ό κ±·κΈ°λ‘ μ€μ
if (Input.GetKeyDown(KeyCode.R)) myRobotAction = RobotRun;//μμ λ©μλλ₯Ό λ°κΈ°λ‘ μ€μ
//μ
λ°μ΄νΈ λ μ νλ μμμ μ€ν
myRobotAction();
}
void RobotWalk()
{
Debug.Log("λ λ.. λ λ.. κ±·λλ€.. λ‘보νΈ..");
}
void RobotRun()
{
Debug.Log("λλ λλ λ΄λ€ λ‘λ΄..");
}
}
2. μμ ν¨ν΄
μμ ν¨ν΄μ λ©μλκ° ν¬νΌ λΌμ΄λΈλ¬λ¦¬λ₯Ό νΈμΆνλ μν©μμ μ¬μ©λλ€.
μμ²ν μμ μ΄ μλ£λλ©΄ λ€μ λ©μΈ ν¨μλ‘ λμμ¨λ€.
μΉμμ μλ£λ₯Ό λ€μ΄λ‘λν λ μ΄ ν¨ν΄μ μ£Όλ‘ μ¬μ©νλ€.
λ€μ΄λ‘λκ° λλλ©΄ λ°μ λ΄μ©μ κ°μ§κ³ νΉμ ν νμ μ²λ¦¬λ₯Ό μ§ννλ ννμ΄λ€.
(μ½λ μλ΅)
3. ν©μ± μμ
λ€μμ ν¨μλ₯Ό νλμ μμμ μ§μ ν μ μλ€.
μ΄ κΈ°λ₯μ λ€μμ κ³΅μ© ν¨μλ₯Ό μ°κ²°ν΄ μ€ννλ €κ³ ν λ λ§€μ° μ μ©νλ€.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeleTest : MonoBehaviour
{
//WorkerManagerμμ
delegate void MyDelegateHook();
MyDelegateHook ActionTodo;
public string WorkerType = "Peon";
//μμν λ μ컀μκ² μμ
μ ν λΉνλ€
void Start()
{
//μ§μμ ν μΌμ΄ λ§λ€
if(WorkerType == "Peon")
{
ActionTodo += DoJob1;
ActionTodo += DoJob2;
}
//κ·Έ μΈ λλ¨Έμ§λ λ€λ₯Έ μΌμ νλ€
else
{
ActionTodo += DoJob3;
}
}
//μ
λ°μ΄νΈμμ ActionToDoμ μ§μ λ μΌμ μννλ€
void Update()
{
ActionTodo();
}
void DoJob1()
{
Debug.Log("μΌμ κ²ν ");
}
void DoJob2()
{
Debug.Log("μλ₯μ μΆ");
}
void DoJob3()
{
Debug.Log("λͺ°λ λͺ¨λ°μΌκ²μ!");
}
}