Notice
Recent Posts
Recent Comments
Link
스토리지
[4.14] Coroutine 본문
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);
}
'Unity > 유니티 기본' 카테고리의 다른 글
[4.15] Inverse Kinematics (IK) - 역운동학 (0) | 2021.04.15 |
---|---|
[4.14] Nav Mesh (0) | 2021.04.14 |
[4.14] Rigidbody를 사용해서 캐릭터 이동 및 회전 (0) | 2021.04.14 |
[4.9] 닷지 게임 (0) | 2021.04.09 |
[4.9] Material & Shader (0) | 2021.04.09 |
Comments