Unity3D

[Unity] C# Delegate 그리고 Event

일등하이 2014. 4. 25. 14:29
반응형

http://gameforfun.tistory.com/70


public class EventTEst : MonoBehaviour {
    CustomEvent ev;
     
    void Awake(){
        ev = new CustomEvent();
        ev.myEvent += new CustomEvent.CustomEventDelegate(e_myEvent);
        ev.myEvent += new CustomEvent.CustomEventDelegate(e_MyEvent2);     
    }
     
    // Use this for initialization
    void Start () {
         
    }
     
    // Update is called once per frame
    void Update () {
        if(Input.anyKeyDown){
            ev.ActivateEvent("ASDASD",2);//키 입력이 발생하면 특정 함수 실행.
        }
    }
     
    void e_myEvent(string s)       
    {
        //approach to sender's field and we can manipulate.
        print("DUDE: " + "   " + s);
    }
     
    void e_MyEvent2(string s){
        print("IM EVENT 2");
    }
}
 
public class CustomEvent
{
    public delegate void CustomEventDelegate(string s);
    public event CustomEventDelegate myEvent;
         
    public void ActivateEvent(string s)
    {      
        myEvent(s);//이벤트 실행 -> myEvent에 등록된 함수들이 s라는 변수를 가지고 실행. 외부에서 실행 못함.
    }                                   
}


반응형