Unity

Delegate, Action, Event

Guk-blog 2020. 3. 23. 10:01
728x90
반응형

쓰면서도 가끔 헷갈리니까

선언과 결과 정리만

 

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

public class Player : MonoBehaviour
{
    public static Player instance;

    public event System.Action onAttack;
    public event System.Action<int> onAttackTwo;

    public delegate void AttackThree(); 
    public event AttackThree onAttackThree;

    public delegate void AttackFour(int dmg);
    public event AttackFour onAttackFour;


    private void Start()
    {
        instance = this;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            onAttack.Invoke();
            onAttackTwo.Invoke(20);
            onAttackThree.Invoke();
            onAttackFour.Invoke(30);
        }
    }
}

 

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

public class Callback : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Player.instance.onAttack += TakeDamage;
        Player.instance.onAttackTwo += TakeDamage;
        Player.instance.onAttackThree += TakeDamage;
        Player.instance.onAttackFour += TakeDamage;
    }

    void TakeDamage()
    {
        Debug.Log("Take Damage");
    }

    void TakeDamage(int dmg)
    {
        Debug.Log("Take Damage "+dmg);
    }


    private void OnDestroy()
    {
        Player.instance.onAttack -= TakeDamage;
        Player.instance.onAttackTwo -= TakeDamage;
        Player.instance.onAttackThree -= TakeDamage;
        Player.instance.onAttackFour -= TakeDamage;
    }
}

Invoke는 선언된 클래스에서만 사용 가능함

public void 를 이용해서 호출하면 다른 클래스에서도 사용가능

예를 들어

public void Test()
    {
        onAttack.Invoke();
        onAttackTwo.Invoke(20);
        onAttackThree.Invoke();
        onAttackFour.Invoke(30);
    }

Player 클래스에서 위와 같이 만들어 주고 

Callback에서 호출해주면 됨

728x90
반응형