이벤트

RudinP·2023년 3월 27일
0

Study

목록 보기
10/211

이벤트의 목적

  • 커플링을 줄이기 위함.
  • 커플링이란, 두 오브젝트가 서로 연결되어있는 정도를 뜻함.
  • 커플링이 많아지면 코드의 수정이 힘들어짐.
  • 따라서, 커플링을 줄이는 것을 지향해야 함.

A, B, C 가 있고, A의 이벤트에 B, C가 메소드를 등록하는 상황일 경우

  • A측을 Publisher 라고 부른다.
  • B, C 처럼 등록하고 대기하는 측을 Subscriber 라 부른다.

ex

  • Character.cs 와 Booster.cs 가 있음.
  • Character.cs 에서 Booster.cs 에 접근하여 메소드를 사용할 예정

Character.cs

public class Character : Monobehaviour
{
	public delegate void Boost(Character target);
    
    public Boost playerBoost;
    
    ~중략~
    
    void Start()
    {
    	playerBoost(this);
    }
}

Booster.cs

public class Booster : Monobehaviour
{
	~중략~
    void Awake()
    {
    	Character player = FindObjectOfType<Character>();
        
        player.playerBoost += HealthBoost; //Delegate
        player.playerBoost += ShieldBoost;
        player.playerBoost += DamageBoost;
    }
}
  • 만약에 플레이어가 ShieldBoost를 안쓰게 된다면, Delegate 등록 해제만 하면 됨.
  • 기존에는 Character.cs 의 코드까지 수정해야 했음.

Delegate로 이벤트를 구현할 수 있지만 유니티에서 별도 제공하는 이유

  • public event Boost playerBoost; 처럼 delegate 형 앞에 event 키워드 사용 가능
  • delegate가 이벤트가 아닌 방향으로 잘못 사용되는 것을 막는 키워드
  • 아래와 같은 문제를 해결 가능. (에러처리)
    	player.playerBoost += HealthBoost;
    		player.playerBoost = DamageBoost; //덮어씌어져버림 **문제**
  • 퍼블리셔 측이 아닌, 구독 측이 이벤트를 발생하지 않도록 방지해줌. (에러처리)
    -(ex): Booster.cs 에서 player.playerBoost(player); 실행
profile
곰을 좋아합니다. <a href = "https://github.com/RudinP">github</a>

0개의 댓글