본 포스트는 https://www.youtube.com/watch?v=70PcP_uPuUc 를 참고하여 작성하였습니다.
Event System을 사용하는 이유
GetComponenet를 사용하지 않기 위함.클래스간 종속성을 제거하기 위함.한 이벤트는 여러 Subscriber(구독자)를 가진다.객체간의 종속성인 '결합도'를 낮추기 위함이다.
EventManager 추가EventManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EventManager : Monobehabiour {
// Action은 Delegator(위임자) 임. 자세한 내용은 디자인 패턴 중 위임자 패턴 참고
// 어느 클래스에서도 ExampleEvent를 사용하기 위해 static으로 선언
public static event Action ExampleEvent;
private void Update() {
if (Input.GetMouseButtonDown(0)) {
// if (ExampleEvent != null)
// ExampleEvent();
ExampleEvent?.Invoke();
}
// 위의 문장과 아래의 문장은 동일
}
ChangeSize.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangeSize : Monobehaviour {
void Start() {
// Delegator에 함수 추가
EventManager.ExampleEvenet += IncreaseSize;
}
private void IncreaseSize() {
transform.localScale = new Vector3(2, 2, 2);
}
// 오브젝트가 삭제되었을 시 이벤트 삭제
private void OnDisable() {
EventManager.ExampleEvent -= IncreaseSize;
}
}
Delegate(위임) 패턴은 중개국과 유사하다고 보면 쉽다.
사용할 함수를 미리 중개국에 위임하고 필요시 중개국에서 사용하는 방식이라고 보면 된다.
ChangeColor 추가하기ChangeColor.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangeColor : MonoBehabiour {
public Color newColor;
void Start() {
EventManager.ExampleEvent += SetNewColor;
}
private void SetNewColor() {
GetComponent<SpriteRenderer>().color = newColor;
}
}