Unity/유니티 기본
[4.14] Coroutine
ljw4104
2021. 4. 14. 12:29
Coroutine Function
- IEnumerator 형식을 반환값으로 가지며 yield return 구문을 어디엔가 포함하고 있는 함수.
- Update처럼 사용이 가능하지만, Update 함수는 시작하자마자 작동하는 것에 반해, Coroutine 함수는 내가 원할 때 호출할 수 있다.
- yield return : 실행을 중지하고 다음 프레임에서 실행을 재개할 수 있게함.
- yield return new WaitForSeconds(float)을 사용해서 지연값을 넣을 수 있다.
- Coroutine의 중복시작을 막기 위해서, 코루틴을 다시 시작할 때 StopCoroutine을 넣고 다시 StartCoroutine하면 됨.
EX) 캐릭터의 움직임을 Coroutine으로 처리
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
this.Move(Input.mousePosition);
}
}
public void Move(Vector3 pos)
{
StartCoroutine("MoveImpl", pos);
}
private IEnumerator MoveImpl(Vector3 pos)
{
this.anim.SetBool("Run", true);
while (true)
{
var dir = (pos - this.transform.position).normalized;
this.transform.Translate(dir * this.speed * Time.deltaTime);
if (Vector3.Distance(this.transform.position, pos) < 0.1f)
{
break;
}
yield return null; //다음 프레임에서 while문 다시 수행
}
this.anim.SetBool("Run", false);
}