스파르타코딩클럽 게임개발
오늘은 스파르타 코딩 클럽 unity 게임 개발 과정 41일차(코루틴에 대해)
코드천자문
2023. 12. 28. 02:36
반응형
Unity 코루틴(Coroutines) 사용 가이드
코루틴이란?
Unity에서 코루틴은 일시 중단 가능한 함수의 실행을 가능하게 하며, 주로 시간에 따른 작업, 비동기 로딩, 순차적 이벤트 처리 등에 사용됩니다.
기본 사용법
코루틴 시작하기
using System.Collections;
using UnityEngine;
public class CoroutineDemo : MonoBehaviour
{
void Start()
{
StartCoroutine(MyCoroutine());
}
IEnumerator MyCoroutine()
{
// 코루틴의 내용
yield return null;
}
}
지연시간 설정하기
IEnumerator MyCoroutine()
{
Debug.Log("작업 시작");
yield return new WaitForSeconds(3); // 3초 동안 대기
Debug.Log("3초 후 작업 실행");
}
코루틴 사용 예제
예제 1: 점차 색상 변경하기
IEnumerator ChangeColor()
{
Renderer renderer = GetComponent<Renderer>();
Color startColor = renderer.material.color;
Color endColor = Color.red;
float duration = 5.0f;
for (float t = 0; t < 1; t += Time.deltaTime / duration)
{
renderer.material.color = Color.Lerp(startColor, endColor, t);
yield return null;
}
}
예제 2: 순차적 이벤트 처리
IEnumerator SequentialEvents()
{
yield return StartCoroutine(EventOne());
yield return StartCoroutine(EventTwo());
}
IEnumerator EventOne()
{
// 이벤트 1의 내용
yield return new WaitForSeconds(2);
}
IEnumerator EventTwo()
{
// 이벤트 2의 내용
yield return new WaitForSeconds(2);
}
주의사항 및 최적화
- 메모리 관리: 장기 실행되는 코루틴은 메모리 사용에 주의해야 합니다.
- 코루틴 중지:
StopCoroutine
과StopAllCoroutines
메소드로 코루틴을 중지할 수 있습니다. - 프레임 관리:
yield return null
은 다음 프레임까지 대기하게 하며, 프레임당 처리량을 조절할 수 있습니다.
주의사항 및 예제
코루틴 사용 시 주의사항
1. 오브젝트 상태 확인
- 코루틴이 실행 중인 객체가 비활성화되거나 파괴되면, 코루틴은 중단됩니다.
- 예제: 코루틴이 실행 중일 때 오브젝트가 파괴되는 경우,
NullReferenceException
오류가 발생할 수 있습니다.
2. 무한 루프 방지
- 코루틴 내에서 조건 없는 무한 루프를 사용하면 게임이 멈출 수 있습니다.
- 예제:
while(true)
와 같은 무한 루프는 항상 탈출 조건을 포함해야 합니다.
3. 동시 실행 코루틴 관리
- 여러 코루틴이 동시에 실행되면 예상치 못한 결과나 성능 저하를 일으킬 수 있습니다.
- 예제: 동시에 많은 수의 코루틴이 실행되어 성능 문제가 발생하는 경우, 코루틴의 수를 제한하거나, 필요한 경우에만 실행하도록 조정해야 합니다.
4. 비동기 작업의 오류 처리
- 코루틴을 이용한 비동기 작업에서 발생하는 오류는 적절히 처리해야 합니다.
- 예제: 파일 로딩, 네트워크 통신 등의 비동기 작업 중 오류 발생 시, 예외 처리를 통해 안정적으로 관리해야 합니다.
코루틴 사용 예제
예제 1: 오브젝트 상태 확인
IEnumerator CheckObjectStateCoroutine()
{
while (true)
{
if (gameObject == null || !gameObject.activeInHierarchy)
{
yield break; // 오브젝트가 비활성화되거나 파괴된 경우, 코루틴 중단
}
yield return null;
}
}
예제 2: 무한 루프 방지
IEnumerator AvoidInfiniteLoopCoroutine()
{
float elapsedTime = 0f;
float maxTime = 10f;
while (elapsedTime < maxTime)
{
elapsedTime += Time.deltaTime;
yield return null;
}
}
예제 3: 동시 실행 코루틴 관리
private int runningCoroutines = 0;
private const int MaxRunningCoroutines = 5;
IEnumerator ManagedCoroutine()
{
if (runningCoroutines >= MaxRunningCoroutines)
{
yield break; // 최대 실행 가능한 코루틴 수를 초과한 경우, 코루틴 실행 중단
}
runningCoroutines++;
// 코루틴 작업
runningCoroutines--;
}
반응형