public class AsyncExample : MonoBehaviour
{
async void Start()
{
Debug.Log("데이터 로딩 시작");
await LoadDataAsync();
Debug.Log("데이터 로딩 완료");
}
async Task LoadDataAsync()
{
await Task.Delay(2000);
}
}
async Task PerformTaskWithExceptionHandlingAsync()
{
try
{
await Task.Delay(1000);
throw new System.Exception("에러 발생");
}
catch (System.Exception e)
{
Debug.LogError($"비동기 작업 중 에러 발생: {e.Message}");
}
}
비동기 작업 중 발생하는 예외를 처리하는 것이 중요하다.
public class FadeScripts : MonoBehaviour
{
void Start()
{
StartCoroutine(FadeOut());
}
IEnumerator FadeOut()
{
float fadeDuration = 3f;
float elapsedTime = 0f;
while (elapsedTime < fadeDuration)
{
elapsedTime += Time.deltaTime;
float alpha = 1 - (elapsedTime / fadeDuration);
yield return null;
}
}
}
코루틴은 게임의 주된 실행 흐름을 방해하지 않으면서
별도의 실행흐름을 만들어 낸다. (완전히 독립적이지는 않음)
코루틴이 어러개 동시에 시작하고, 각각 독립적으로 실행될 수 있다.
void Start()
{
StartCoroutine(CoroutineA());
StartCoroutine(CoroutineB());
}
IEnumerator CoroutineA()
{
yield return new WaitForSeconds(2);
}
IEnumerator CoroutineB()
{
yield return new WaitForSeconds(3);
}