public class Delegate : MonoBehaviour
{
delegate int Calculator(int num1, int num2);
private int Add (int num1, int num2)
{
return num1 + num2;
}
private int Sud(int num1, int num2)
{
return num1 - num2;
}
private void Start()
{
Calculator calculator = new Calculator(Add);
Debug.Log(calculator(10, 20));
}
}
기본 사용법이다.
Player가 있고 Enemy가 있을 때 Player가 q를 입력하면 Enemy의 대사가 뜨게 유니티 이벤트를 사용 해 만든 것 이다. Find를 사용하면 좋지 않지만 이번 예제만 넘어가자
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInput : MonoBehaviour
{
// 플레이어가 qwer 입력을 하면 그게 맞는 대화가 나온다.
private Enemy enemy;
void Start()
{
enemy = GameObject.Find("Enemy").GetComponent<Enemy>();
enemy.EnemyHit.AddListener(enemy.EnemyHitSay);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class Enemy : MonoBehaviour
{
public UnityEvent EnemyHit = new UnityEvent();
void Update()
{
if (Input.GetKeyDown(KeyCode.Q))
{
EnemyHit.Invoke();
}
}
public void EnemyHitSay()
{
Debug.Log("아파용");
}
}
이벤트를 실행시키는 주체(Enemy) 가 이벤트와 이벤트를 실행요청(Invoke)을 하는것 이벤드가 실행됬다는걸 듣는(AddListener) 를 구분하여 잘 설계해야 한다.
다음엔 생성됬을 때 플레이어에게 알리는걸 이벤트로 해봐야겠다..