ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 유니티 비동기 로딩 - 로딩 씬
    Unity 2024. 1. 12. 21:04
    반응형

    안녕하세요

    오늘은 유니티 로딩 화면 만드는 방법입니다.

    유니티에서 제공하는 LoadSceneAsync을 이용한 비동기 로딩 씬입니다.

     

    [변수]

    #region 변수
    [SerializeField] private TMP_Text loadingText;
    [SerializeField] private Image loadingImg;
    [SerializeField] private float rotateSpeed;
    
    private static string nextScene;
    #endregion // 변수
    • 시간이 변화함에 따라 증가하는 숫자를 보여줄 Text 변수
    • 씬이 전환되기전 보여줄 이미지 (이미지를 회전시키기 위한 Speed) 변수

    [정적 함수]

    /** 씬을 로드한다 */
    public static void LoadScene(string sceneName)
    {
        nextScene = sceneName;
        SceneManager.LoadScene("LoadingScene");
    }
    • 매개변수로 변경할 씬 이름을 받아와 로딩씬을 불러옵니다

    [메인 구현부분]

    /** 로딩중일때 Bar를 채운다 */
    private IEnumerator LoadSceneProcess()
    {
        AsyncOperation asyncOper = SceneManager.LoadSceneAsync(nextScene);
        asyncOper.allowSceneActivation = false;
    
        float loadingPercent = 0f;
    
        float unsacledTimer1 = 0.0f;
        float unsacledTimer2 = 0.0f;
    
        while (!asyncOper.isDone)
        {
            yield return null;
    
            // 이미지 회전
            loadingImg.transform.Rotate(new Vector3(0, 0, rotateSpeed * Time.unscaledDeltaTime));
    
            // 씬 로딩이 완료가 안됐을 경우
            if (asyncOper.progress < 0.9f)
            {
                unsacledTimer1 += Time.unscaledDeltaTime;
    
                if (loadingPercent <= 89f)
                {
                    loadingPercent = Mathf.Lerp(loadingPercent, 89f, unsacledTimer1);
                    loadingText.text = Mathf.Round(loadingPercent).ToString() + " %";
                }
            }
            else
            {
                unsacledTimer2 += Time.unscaledDeltaTime;
    
                loadingPercent = 89f;
                loadingPercent = Mathf.Lerp(loadingPercent, 100f, unsacledTimer2);
                // 반올림
                loadingText.text = Mathf.Round(loadingPercent).ToString() + " %";
    
                // loadingPercent가 100이라면 씬 전환
                if (loadingPercent == 100f)
                {
                    asyncOper.allowSceneActivation = true;
                }
            }
        }
    }
    • 로딩이 끝날때 까지 반복한다
    • allowSceneActivation이 false로 설정되어있을 경우 0.9에서 진행이 중지되고, isDone은 false로 유지되기 때문에
      조건문을 사용해 구현한다. (https://docs.unity3d.com/kr/current/ScriptReference/AsyncOperationallowSceneActivation.html)
    • allowSceneActivation : 씬의 로딩이 완료되면 바로 씬을 불러올 것인지, 기다릴 것인지 정할 수 있다
    • isDone : 로딩이 끝났는지 결과를 반환합니다 (Read Only)
    • priority : 비동기 호출 순서를 정할 수 있습니다
    • progress : 현재 로딩의 진행 상황을 0 - 1 까지의 숫자로 반환합니다 (Read Only)
    반응형
Designed by Tistory.