[unity/UniTask] UniTask를 활용하여 백그라운드에서 리소스(texure) 로드하는 방법
[unity/UniTask] UniTask를 활용하여, 백그라운드에서 리소스 로드하는 방법
일반적으로 async/await를 통하여 비동기 처리를 처리를 하는데,
gameobject/texture등 항상 메인쓰레드에서 돌아야하기때문에 비동기처리가 쉽지않다
UniTask를 활용하여 쉽게 해보도록하자
#UniTask
UniTask는 유니티용 async-await 통합패키지이다
https://github.com/Cysharp/UniTask
#UniTask에 관해 참고하면 좋은 블로그
GitHub - Cysharp/UniTask: Provides an efficient allocation free async/await integration for Unity.
Provides an efficient allocation free async/await integration for Unity. - GitHub - Cysharp/UniTask: Provides an efficient allocation free async/await integration for Unity.
github.com
https://velog.io/@jinuku/UniTask-%EC%95%8C%EC%95%84%EB%B3%B4%EA%B8%B0
#리소스 로드할 UnjTask 기반의 함수
private async UniTask<Texture2D> GetImageAsync(string path)
{
UnityWebRequest www = UnityWebRequestTexture.GetTexture("file://" + path);
await www.SendWebRequest();
if (www.isNetworkError || www.isHttpError) throw new Exception(www.error);
return ((DownloadHandlerTexture)www.downloadHandler).texture;
}
#테스트 비동기 함수
약 100장의 리소스를 동시에 5번 로드해보자
async
Task
LoadImage1(int idx)
{
for (int i = idx; i < (idx+100); i++)
{
var texture = await GetImageAsync(@"c:\a\" + i.ToString("00000") + ".jpg");
SequenceList1.Add(texture);
}
Debug.Log("200장 로드 완료 1번:" + DateTime.Now);
Debug.Log("1번:" + SequenceList1.Count);
}
void Update()
{
if (Input.GetKeyUp("1"))
{
Debug.Log("함께시작:"+DateTime.Now);
_ = LoadImage1(1);
_ = LoadImage2(1001);
_ = LoadImage3(2001);
_ = LoadImage4(3001);
_ = LoadImage5(4001);
}
}
3초동안 500장로드를 비동기로 처리하였다
#UniTask #비동기 #async #await #이미지 #시퀀스