async메서드를 위한 AsyncEventManager

2025. 4. 15. 22:46·코드 및 공부/최적화

유니티 버전 - 2022.3.59f1

 

 

 

 

 

목차


  • 기존 코드
  • AsyncEventManager

 

 

 

 

 

기존 코드


기존 EvnetManager에 등록된 OnExtendUI는 ShowPopup을 .Forget()하고 최하단에서 비활성화되어있는 슬롯 백그라운드만 활성화 시켜주었기에, 처음 팝업 로드시에 팝업을 불러오는 지연시간이 발생하고, 백그라운드 활성화 후 팝업이 살짝 늦게 로드되어 빈 화면이 보이는 경우가 발생, 팝업 로드를 await한 후 백그라운드를 활성화 하도록 할 예정입니다

private void OnExtendUI(object args)
{         
  if (!IsUIOpened)
  {
    ShowPopup<PlayerInfomationPopup>().Forget();
             
    OnExtendUI(IsUIOpened);
  }
  else
  {
  OnExtendUI(IsUIOpened);
             
  Managers.UI.CloseAllPopup();
  }
         
  OnExtendUI(IsUIOpened);
}

 

 

 

OnExtendUI를 async로 바꾸며 메서드를 기존 EventManager에 등록할 수 없었습니다

private async UniTask OnExtendUI(object args)
{
    if (!IsUIOpened)
    {
      await ShowPopup<PlayerInfomationPopup>();
    }
    else
    {
      Managers.UI.CloseAllPopup();
    }
          
    OnExtendUI(IsUIOpened);
}

 

 

 

 

 

AsyncEventManager


기존 EventManager를 이용하여, 비동기 메서드 또한 등록, 실행 가능하도록 AsyncEventManager를 만들어 주었습니다

using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using UnityEngine;


public delegate UniTask AsyncEventListener(object args);


public static class AsyncEventManager
{
    private static readonly Dictionary<GameEventType, List<AsyncEventListener>> _asyncEventListenerDic = new Dictionary<GameEventType, List<AsyncEventListener>>();


    /// <summary>
    /// 비동기 이벤트 구독
    /// </summary>
    public static void Subscribe(GameEventType type, AsyncEventListener listener)
    {
        if (!_asyncEventListenerDic.TryGetValue(type, out List<AsyncEventListener> list))
        {
            list = new List<AsyncEventListener>();

            _asyncEventListenerDic[type] = list;
        }

        list.Add(listener);
    }

    /// <summary>
    /// 비동기 이벤트 구독 취소
    /// </summary>
    public static void Unsubscribe(GameEventType type, AsyncEventListener listener)
    {
        if (_asyncEventListenerDic.TryGetValue(type, out List<AsyncEventListener> list))
        {
            list.Remove(listener);

            if (list.Count == 0)
            {
                _asyncEventListenerDic.Remove(type);
            }
        }
    }

    /// <summary>
    /// 비동기 이벤트 실행
    /// </summary>
    public static async UniTask Dispatch(GameEventType type, object args)
    {
        if (!_asyncEventListenerDic.TryGetValue(type, out List<AsyncEventListener> list)) return;

        foreach (AsyncEventListener listener in list)
        {
            try
            {
                await listener.Invoke(args);
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
        }
    }
}

 

 

 

이제 팝업을 처음 띄울때도 지연시간으로 인한 빈 백그라운드 출력 없이 팝업과 함께 표시되도록 할 수 있었습니다

public override void Init()
{
    base.Init();
        
    AsyncEventManager.Subscribe(GameEventType.OnInventory, OnExtendUI);
}

'코드 및 공부 > 최적화' 카테고리의 다른 글

Int값을 .ToString() 후 캐싱하여 사용하기  (0) 2025.04.01
딕셔너리의 GetValueOrDefault()  (0) 2025.03.27
ReferenceEquals()를 이용한 null 비교 수행  (0) 2025.03.25
CommandSceheduler를 이용한 메서드 순차 실행  (0) 2025.03.22
그래픽 옵션(Quality) 변경하기  (0) 2025.02.04
'코드 및 공부/최적화' 카테고리의 다른 글
  • Int값을 .ToString() 후 캐싱하여 사용하기
  • 딕셔너리의 GetValueOrDefault()
  • ReferenceEquals()를 이용한 null 비교 수행
  • CommandSceheduler를 이용한 메서드 순차 실행
ekrxjvpvj0110
ekrxjvpvj0110
유니티 개발 관련 자료
  • ekrxjvpvj0110
    ekrxjvpvj0110의 유니티 개발
    ekrxjvpvj0110
    • 전체 글 (75)
      • 안드로이드 (1)
        • 에셋 관리 (1)
      • 코드 및 공부 (73)
        • 이론 (4)
        • 데이터 관리 (11)
        • 입력 관리 (9)
        • 최적화 (10)
        • UI (3)
        • 통신 (0)
        • 카메라 (3)
        • 오디오 (3)
        • 물리 (3)
        • 씬 (6)
        • 기타 (21)
        • 분류없음 (0)
  • 인기 글

  • hELLO· Designed By정상우.v4.10.3
ekrxjvpvj0110
async메서드를 위한 AsyncEventManager
상단으로

티스토리툴바