티스토리 뷰

이건 C#에 좀 더 가까운 내용.... C#에서는 기본적으로 EventArgs, EventHandler라는 클래스를 제공한다. 이 녀석을 활용해서 가독성 좋게 Event Driven Programming을 할 수 있다.


게임에서 라운드 개념을 도입한다고 생각해보자. 라운드가 증가될 때마다 오브젝트들이 변경되어야 할 것이다. 이걸 좀 예쁘게 구현하고 싶다.

다양한 방법이 있겠지만 위에서 언급한 EventArgs 클래스, EventHandler 클래스를 이용한 방법으로 구현해보자.


EventHandler는 List<>와 비슷한 방법으로 생성할 수 있다. List의 type에는 제한이 없지만 EventHandler에는 EventArgs 클래스만이 들어갈 수 있다. 즉, EventArgs 클래스를 상속받은 클래스를 Handler로 broadcasting 할 수 있다는 뜻이다.


public class EventRoundChange : EventArgs
{
    public int round;

}


단순히 round 값 자체만 argument 로 넣어서 뿌려줄 생각이다. EventHandler를 선언한다. 그리고 round의 setter에서 이벤트를 생성하여 broadcasting 한다. 특이한 점은 인스턴스를 새로 allocate 해줄 필요가 없다는 점이다. List나 Dictionary 같은 Generic Collection을 사용할 경우와 다른 점이다. 


public event EventHandler<EventRoundChangeOnRoundChangeCallbacks;


int _currentRound;
public int CurrentRound {
    get {
        return _currentRound;
    }
    private set {
        _currentRound = value;
        var e = new EventRoundChange {round = this.CurrentRound};
        OnRoundChangeCallbacksthise );
    }
}


물론 이걸로 끝이 아니라 EventHandler에 callback을 등록하는 절차가 필요하다.


RoundManager roundManager = GameObject.Find ("RoundManager").GetComponent<RoundManager> ();

roundManager.OnRoundChangeCallbacks += this.OnRoundChanged;


...


abstract protected void OnRoundChanged (object senderEventRoundChange e);


+ 연산자를 이용하여 callback을 추가한다. 나 같은 경우엔 Enemy 클래스에서 OnRoundChange를 추가했는데, 이 Enemy 클래스가 abstract 클래스이다보니 위와 같은 모양새가 되었다. sender는 이 이벤트를 뿌려주는 클래스이다. 이번 경우에는 RoundManager 클래스가 되겠다. 더욱 자세한 설명은 레퍼런스를 찾아보시길.... 위에서 언급한 바와 같이 Generic Collection과 delegate, System.Action 클래스를 이용하여 구현할 수도 있다. 나 같은 경우 예전 NotificationCenter를 구현할 때는 EventHandler를 쓰지 않고 Dictionary와 delegate를 이용하여 구현했었다. 정해진 답은 없는거니까 본인이 좋은대로 구현하면 되겠다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday