Notice
Recent Posts
Recent Comments
Link
박민혁의 개발
게임 로딩 구현 본문
- 코루틴(Coroutine)
- 코루틴은 비동기적으로 실행되는 함수로, 특정 코드 블럭의 실행을 일시적으로 중지하고 다시 시작할 수 있게 해줍니다.
- IEnumerator 리턴 타입의 함수에서 **yield return**을 사용하여 코루틴을 구현할 수 있습니다.
- StartCoroutine 함수를 통해 코루틴을 시작할 수 있고, StopCoroutine 함수를 통해 코루틴을 중지할 수 있습니다.
- 코루틴은 프레임 간의 지연, 비동기 작업, 시간에 따른 애니메이션 등의 작업에 주로 사용됩니다.
- **yield return null**은 다음 프레임까지 대기를 의미하고, **yield return new WaitForSeconds(n)**은 n초 동안 대기를 의미합니다.
- 코루틴은 별도의 스레드에서 실행되지 않습니다. 따라서 Unity의 메인 스레드에서 안전하게 Unity API를 호출할 수 있습니다.
- 코루틴은 일반 함수와는 다르게, 실행을 일시 중단하고 나중에 다시 시작할 수 있어, 시간 지연, 반복, 조건부 대기 등의 작업을 수행할 때 매우 유용합니다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoadingSceneController : MonoBehaviour
{
static string nextScene;
[SerializeField] Image progressBar;
public static void LoadScene(string sceneName)
{
nextScene = sceneName;
SceneManager.LoadScene("LoadingScene");
}
// Start is called before the first frame update
void Start()
{
StartCoroutine(LoadSceneProcess());
}
IEnumerator LoadSceneProcess()
{
AsyncOperation op = SceneManager.LoadSceneAsync(nextScene);//비동기방식
op.allowSceneActivation = false ; // 로딩이 90퍼때 멈추게함 = 로딩화면 보여주기 너무 짧으면 있는 의미가 없다고함 ,
// 에셋번들 리소스 받아오는 시간확보 (씬의 로딩이 더빠를수 있음)
float timer = 0f;
while (!op.isDone) // op가 끝나지않으면 반복
{
yield return null; //제어권을 돌려줘서 로딩바가 차게해줌
if (op.progress < 0.9f) //로딩이 90% 미만이면 로딩바 업데이트해줌
{
progressBar.fillAmount = op.progress;
}
else
{
timer += Time.unscaledDeltaTime;
progressBar.fillAmount = Mathf.Lerp(0.9f, 1f, timer); // 0.9에서 1로 1초에걸쳐채움
if (progressBar.fillAmount >= 1f)
{
op.allowSceneActivation = true;
yield break;
}
}
}
}
}
'TIL' 카테고리의 다른 글
프로젝트 마무리 (0) | 2023.10.04 |
---|---|
유니티 오브젝트 리스폰 시키기 (0) | 2023.09.27 |
메타 파일이 왜 생기는 걸까? (0) | 2023.09.25 |
스크립터블 오브젝트 주의사항 (0) | 2023.09.22 |
SerializeField 와 HideInInspector의 용도 (0) | 2023.09.21 |