코루틴 (Coroutine)
* 코루틴 (Coroutine) -> 시간 절약 X! , 작업을 분산
* 작업을 다수의 프레임에 분산하여 처리하는 비동기식 작업
* 실행을 일시정지하고 중단한 부분부터 재개하여 처리하는 것으로 작업을 분산처리함
* 코루틴은 스레드가 아니며 코루틴의 작업은 메인 스레드에서 실행
IEnumerator Routine()
{
yield return null;
yield return new WaitForSeconds(1f);
yield return new WaitForSecondsRealtime(1f);
yield return new WaitForFixedUpdate();
yield return new WaitForEndOfFrame();
yield return new WaitUntil(() => Input.GetKeyDown(KeyCode.Space));
}
[SerializeField] Rigidbody rigid;
[SerializeField] float junpPower;
private Coroutine countDownCoroutine;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (countDownCoroutine == null)
{
countDownCoroutine = StartCoroutine(Routine());
}
}
if (Input.GetKeyDown(KeyCode.Escape))
{
if (countDownCoroutine != null)
{
StopCoroutine(countDownCoroutine);
countDownCoroutine = null;
}
}
}
<코루틴 반복 작업>
IEnumerator Routine()
{
WaitForSeconds delay = new WaitForSeconds(1f);
Debug.Log(5);
yield return delay;
Debug.Log(4);
yield return delay;
Debug.Log(3);
yield return delay;
Debug.Log(2);
yield return delay;
Debug.Log(1);
yield return delay;
Debug.Log(5);
yield return new WaitForSeconds(1f);
Debug.Log(4);
yield return new WaitForSeconds(1f);
Debug.Log(3);
yield return new WaitForSeconds(1f);
Debug.Log(2);
yield return new WaitForSeconds(1f);
Debug.Log(1);
yield return new WaitForSeconds(1f);
Debug.Log("점프 대기 시작");
yield return new WaitForSeconds(5f);
Debug.Log("점프!!");
rigid.AddForce(Vector3.up * junpPower, ForceMode.Impulse);
countDownCoroutine = null;
}
유니티이벤트
public class UnityEventTester : MonoBehaviour
{
public UnityEvent myEvent;
public event UnityAction OnDied;
public event Action myDelegate;
private void Awake()
{
}
public void Test(){}
private void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
myEvent.Invoke();
}
}
}