내일배움캠프

내일배움캠프: 비동기 씬을 이용한 콜백

pracumj 2024. 12. 19. 22:39

오늘은 Unity에서 비동기 씬 로드와 콜백을 활용해보았다 

    public IEnumerator LoadSceneAsync(SceneName sceneName, Action<float> uiAction = null, Action callBack = null)
    {
        
        AsyncOperation operation = LoadSceneAsync(sceneName);
        operation.allowSceneActivation = false; // 씬 자동 활성화 방지

        float fakeLoadingTime = 2.0f;
        float elapsedFakeTime = 0f;


      
        while (!operation.isDone)
        {
            float progress = Mathf.Clamp01(operation.progress / 0.9f);

            elapsedFakeTime += Time.deltaTime;

            float fakeProgress = Mathf.Clamp01(elapsedFakeTime / fakeLoadingTime);
            
            uiAction?.Invoke(fakeProgress);


            if (progress >= 0.9f && elapsedFakeTime >= fakeLoadingTime)
            {
                operation.allowSceneActivation = true;
            }

            yield return null;
        }
        
        uiAction?.Invoke(1f); 
        callBack?.Invoke(); 
        yield return new WaitForSeconds(0.5f); 
    }

 

callback 함수를 통해 씬이 로딩이 된 후 처리를 할 수 있었다.