이전에 MonoBehaviour를 상속받지 않는 클래스에서 코루틴을 사용하고 싶었지만 코드에서 Coroutine이 찾아지지 않았다(에러났다는 뜻). 그래서 이 때 처음 알게 된 사실은 코루틴은 MonoBehaviour에 종속되어 있다는 것이다!!! 당시에는 당황스러워서 그냥 해당 클래스에 MovoBehaviour를 상속받았다..ㅋㅋ
오늘은 Managers에서 통합 관리당하는(?) WaveManager 클래스에서 코루틴을 사용하고 싶었다. 오늘은 다른 방법으로 MonoBehaviour를 상속받지 않는 클래스에서 코루틴을 사용할 수 있었다. 우리팀 팀원분께서 알려주신 방법인데 감동받아서 TIL로 남긴다.
상윤님 천재세요!?!?
직접 실행하려면 반드시 MonoBehaviour의 StartCoroutine()을 통해야 한다. 두 가지 해결 방법이 있었다.
방법 1. Managers는 MonoBehaviour를 상속받고 있으므로 대신 코루틴을 돌려주기
static 인스턴스로 MonoInstance를 추가로 만들어줘서 Managers.StartCoroutine(MyCoroutine()); 와 같은 숏컷 형태로 사용할 수 있어졌다.
(MonoInstance가 없어도 Managers.Instance.StartCoroutine(MyCoroutine()); 와 같이 사용할 수 있다.)
public class Managers : MonoBehaviour
{
public static Managers Instance { get; private set; }
public static MonoBehaviour MonoInstance { get; private set; }
public static readonly GameManager Game = new();
public static readonly PoolManager Pool = new();
public static readonly ResourceManager Resource = new();
public static readonly SceneManager Scene = new();
public static readonly UIManager UI = new();
public static readonly DataManager Data = new();
public static readonly WaveManager Wave = new();
private void Awake()
{
if (Instance != null)
{
Destroy(gameObject);
return;
}
Instance = this;
MonoInstance = this;
DontDestroyOnLoad(this);
Game.Initialize();
Pool.Initialize();
Data.Initialize();
Scene.Initialize();
Wave.Initialize();
}
public new static Coroutine StartCoroutine(IEnumerator coroutine)
{
return MonoInstance.StartCoroutine(coroutine);
}
public new static void StopCoroutine(Coroutine coroutine)
{
MonoInstance.StopCoroutine(coroutine);
}
}
방법 2. 코루틴 실행 전용 클래스 만들기
이것도 신박한 아이디어라고 느껴졌다.
public class CoroutineRunner : MonoBehaviour
{
private static CoroutineRunner _instance;
public static CoroutineRunner Instance
{
get
{
if (_instance == null)
{
var go = new GameObject("[CoroutineRunner]");
_instance = go.AddComponent<CoroutineRunner>();
DontDestroyOnLoad(go);
}
return _instance;
}
}
}
사용할 땐 CoroutineRunner.Instance.StartCoroutine(ExCoroutine()); 이렇게 사용하면 되겠쥐용?
'프로젝트 일지 > Unity' 카테고리의 다른 글
[Unity/TIL] 프리팹 Variant (2) | 2025.04.15 |
---|---|
[Unity/TIL] 방치형 게임에서 유닛 스폰 최적화 구조 설계하기 (0) | 2025.04.14 |
[Unity/TIL] 싱글톤 매니저 관리 (2) | 2025.04.10 |
[Unity/TIL] Addressable 연구(2) (2) | 2025.04.09 |
[Unity/TIL] Addressable 연구 (3) | 2025.04.08 |