[Unity] Scene 전환시 Loading Scene 만들기
2020. 10. 9. 16:05ㆍ[Unity] 게임 개발
반응형
개발 중 Main Scene -> Game Scene으로 넘어갈 때 Game Scene 의 많은 리소스들 때문에 버퍼링이 발생하는 것을 발견하고
Loading 화면을 만들기로 결정.
SceneLoader.cs
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class SceneLoader : MonoBehaviour
{
protected static SceneLoader instance;
public static SceneLoader Instance
{
get
{
if (instance == null)
{
var obj = FindObjectOfType<SceneLoader>();
if (obj != null)
{
instance = obj;
}
else
{
instance = Create();
}
}
return instance;
}
private set
{
instance = value;
}
}
[SerializeField]
private CanvasGroup sceneLoaderCanvasGroup;
[SerializeField]
private Image progressBar;
private string loadSceneName;
public static SceneLoader Create()
{
var SceneLoaderPrefab = Resources.Load<SceneLoader>("SceneLoader");
return Instantiate(SceneLoaderPrefab);
}
private void Awake()
{
if (Instance != this)
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
}
public void LoadScene(string sceneName)
{
gameObject.SetActive(true);
SceneManager.sceneLoaded += LoadSceneEnd;
loadSceneName = sceneName;
StartCoroutine(Load(sceneName));
}
private IEnumerator Load(string sceneName)
{
progressBar.fillAmount = 0f;
yield return StartCoroutine(Fade(true));
AsyncOperation op = SceneManager.LoadSceneAsync(sceneName);
op.allowSceneActivation = false;
float timer = 0.0f;
while (!op.isDone)
{
yield return null;
timer += Time.unscaledDeltaTime;
if (op.progress < 0.9f)
{
progressBar.fillAmount = Mathf.Lerp(progressBar.fillAmount, op.progress, timer);
if (progressBar.fillAmount >= op.progress)
{
timer = 0f;
}
}
else
{
progressBar.fillAmount = Mathf.Lerp(progressBar.fillAmount, 1f, timer);
if (progressBar.fillAmount == 1.0f)
{
op.allowSceneActivation = true;
yield break;
}
}
}
}
private void LoadSceneEnd(Scene scene, LoadSceneMode loadSceneMode)
{
if (scene.name == loadSceneName)
{
StartCoroutine(Fade(false));
SceneManager.sceneLoaded -= LoadSceneEnd;
}
}
private IEnumerator Fade(bool isFadeIn)
{
float timer = 0f;
while (timer <= 1f)
{
yield return null;
timer += Time.unscaledDeltaTime * 2f;
sceneLoaderCanvasGroup.alpha = Mathf.Lerp(isFadeIn ? 0 : 1, isFadeIn ? 1 : 0, timer);
}
if (!isFadeIn)
{
gameObject.SetActive(false);
}
}
}
그 후 Scene을 넘겨줄 때
SceneLoader.Instance.LoadScene("Field1");
사용하고 SceneLoader Prefab 제작하여 Resources 폴더에 넣어줌.
실행 결과
Main Scene => Game Scene 갈때 검은 화면에 초록색 로딩바 생성
반응형
'[Unity] 게임 개발' 카테고리의 다른 글
[Unity] UI관리 기법 (0) | 2020.11.02 |
---|---|
[Unity] 싱글톤 패턴 매니저 (0) | 2020.11.01 |
[Unity] iTween Move 함수 사용 (0) | 2020.08.13 |
[Unity]Camera View 조절 (0) | 2020.08.10 |
[Unity 3D]랭킹 구현(MySQL, Photon Network) (0) | 2020.07.28 |