RuntimeInitializeOnLoadMethod 어느 씬에서나 시작 시 실행되는 함수

 

유니티의 Attribute 중에는 게임 시작 시 실행되는 메서드를 위한 RuntimeInitializeOnLoadMethod 가 존재한다. 

Unity Documentation : RuntimeInitializeOnLoadMethodAttribute
https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html

 

 

RuntimeInitializeOnLoadMethod의 특징

1. 게임이 시작되면 자동으로 실행되며, 그 순서는 보장되지 않는다.

2. non-MonoBehaviour 클래스에서도 동작한다.

3. static 메서드에만 적용 가능하다.

 

 

RuntimeInitializeOnLoadMethod의 프로퍼티

애트리뷰트에 같이 넘길 수 있는 프로퍼티는 loadType이 있다.

용도에 따라 5개가 존재하며, 기본은 AfterSceneLoad 이다.

이 경우 실행시점이 Awake 이후, Start이전이다.

Awake이전에 실행하고 싶다면 다른 타입으로 설정할 것.

 

 

사용 예시

나는 주로 프로젝트에서 전역적으로 사용되는 매니저(사운드, 리소스 등)를 초기화할 때 사용하였다.

public static class Bootstrapper
{
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    public static void Execute()
    {
        // 이런식으로 객체를 초기화 하는 경우도 있고
        //var obj = Addressables.InstantiateAsync("Systems").WaitForCompletion();
        //Object.DontDestroyOnLoad(obj);

        // 직접 각 매니저들을 초기화할 수도있다.
        ResourceManager.Instance.Init();
        SoundManager.Instance.Init();
    }
}

 

 

 

 

댓글

Designed by JB FACTORY