본문 바로가기

TIL

23.11.01

비동기적으로 씬 로딩하기

유니티에는 SceneManager라는 클래스가 존재하는데, 게임내 다양한 장면(Scene)을 관리하고 전환하는데 사용되는 유용한 도구입니다.

 

씬 이동

LoadScene을 사용하면 다른 씬으로 전환할 수 있습니다. 하지만 씬을 전환하기 위해서 Build에서 전환할 씬을 등록해야 합니다.

using UnityEngine;
using UnityEngine.SceneManagement;

// 다른 장면으로 전환하기
SceneManager.LoadScene("씬 이름");
SceneManager.LoadScene(Scene Index);

 

비동기 씬 이동

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class LoadingSceneManager : MonoBehaviour
{
    public static string nextScene;
    [SerializeField] Slider progressBar;

    private void Start()
    {
        StartCoroutine(LoadScene());
    }

    public static void LoadScene(string sceneName)
    {
        nextScene = sceneName;
        SceneManager.LoadScene("LoadingScene");
    }

    IEnumerator LoadScene()
    {
        yield return null;
        AsyncOperation op = SceneManager.LoadSceneAsync(nextScene);
        op.allowSceneActivation = false;
        float timer = 0.0f;
        while (!op.isDone)
        {
            yield return null;
            timer += Time.deltaTime;
            if (op.progress < 0.9f)
            {
                progressBar.value = Mathf.Lerp(progressBar.value, op.progress, timer);
                if (progressBar.value >= op.progress)
                {
                    timer = 0f;
                }
            }
            else
            {
                progressBar.value = Mathf.Lerp(progressBar.value, 1f, timer);
                if (progressBar.value == 1.0f)
                {
                    op.allowSceneActivation = true;
                    yield break;
                }
            }
        }
    }
}

 

'TIL' 카테고리의 다른 글

23.11.03  (0) 2023.11.07
23.11.02  (0) 2023.11.07
23.10.31  (0) 2023.11.01
23.10.30  (0) 2023.11.01
23.10.27  (0) 2023.10.30