유니티 로딩 화면 구현 ( Unity Loading system )

참고 : http://wergia.tistory.com/59

 

 

# 방법 1 : 여러가지 씬을 가지고 있고, 로딩 씬은 한개만을 사용할 때.

 

 1번 스크립트는 다른씬에서 로딩씬으로 전환시켜주는 static 함수랑, 

로딩 씬에서 로딩을 직접 관리하는 기능이 하나의 스크립트로 합쳐진 형태.

 

열고싶은 씬 이름을 인자로 보내는 static 함수를 호출하면 로딩 씬을 열고,

로딩 씬에 미리 만들어놓은 1번 스크립트의 start가 호출되어 로딩이 시작되는 것.

nextScene(열고싶은 씬)의 이름은 static 변수이기 때문에 씬 전환전에 세팅이 되어서 로딩씬으로 넘어가서도 남아있다.

 

 

[ 1번 스크립트 ]

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
 
public class LoadingSceneManager : MonoBehaviour
{
    public static string nextScene;
 
    [SerializeField]
    Image progressBar;
 
    private void Start()
    {
        StartCoroutine(LoadScene());
    }
 
    string nextSceneName;
    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.fillAmount = Mathf.Lerp(progressBar.fillAmount, 1f, timer);
 
                if (progressBar.fillAmount == 1.0f)
                    op.allowSceneActivation = true;
            }
            else
            {
                progressBar.fillAmount = Mathf.Lerp(progressBar.fillAmount, op.progress, timer);
                if (progressBar.fillAmount >= op.progress)
                {
                    timer = 0f;
                }
            }
        }
    }
}

 

 

[ 2번 스크립트 ] 

 - 열고싶은 씬을 인자로 호출만 하는 형태. 다음 씬을 열고싶은 시점에 아래와 같이 사용하면 된다.

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestCode : MonoBehaviour
{

    // Use this for initialization
    void Start ()
    {
        LoadingSceneManager.LoadScene("Scene2");
    }
}

 

 

# 방법2 : 열고 싶은 씬이 한개밖에 없어서, 시작화면->로딩->플레이화면 으로 간단하게 구현하는 경우

 

로딩 프로그래스 바 없이 팁 등을 보여주고

로딩이 끝나면 터치등으로 can Open을 true로 만들어서 씬을 열 수 있게 하는 형태.

터치가 필요없다면 canOpen의 초기값을 true로 선언하면된다.

 

    private AsyncOperation async; // 로딩
    private bool canOpen = false;

    void Start ()
    {
        StartCoroutine("Load");
    }

    // 로딩 스크린에서 팁 등을 알려주는 경우. 버튼을 눌러 시작합니다 등을 표시
    // 필요없다면 canOpen을 처음부터 true로 초기화하면됨.
    public void SetCanOpen()
    {
        canOpen = true;
    }
    
    // 로딩
    IEnumerator Load()
    {
        async = SceneManager.LoadSceneAsync("Main"); // 열고 싶은 씬
        async.allowSceneActivation = false;

        while (!async.isDone)
        {
            progress = async.progress;

            yield return true;

            if (canOpen)
                async.allowSceneActivation = true;
        }
    }

 

댓글

Designed by JB FACTORY