[Unity] Event System의 이해

이경현·2024년 2월 15일

유니티

목록 보기
4/4

본 포스트는 https://www.youtube.com/watch?v=70PcP_uPuUc 를 참고하여 작성하였습니다.


Event System을 사용하는 이유

  1. GetComponenet를 사용하지 않기 위함.
  2. 클래스간 종속성을 제거하기 위함.
  3. 한 이벤트는 여러 Subscriber(구독자)를 가진다.
객체간의 종속성인 '결합도'를 낮추기 위함이다.

1. 마우스 왼쪽 클릭에 커지는 사각형 만들기

  1. 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(); 
		}
        // 위의 문장과 아래의 문장은 동일
}
  1. 적당한 사각형 스프라이트 추가

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(위임) 패턴은 중개국과 유사하다고 보면 쉽다.
사용할 함수를 미리 중개국에 위임하고 필요시 중개국에서 사용하는 방식이라고 보면 된다.


2. 마우스 왼쪽 클릭에 색깔이 달라지는 사각형 만들기

  1. 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;
	}
}
profile
게임 개발자 지망생

0개의 댓글