본문 바로가기

Unity

[Unity] WaitForEndOfFrame()으로 좌표 계산 문제 해결

플레이어가 180도 급전환할 때 체력바의 좌표가 튀는 문제가 있었다.

카메라 이동이 아직 반영되기 전에 WorldToScreenPoint()가 호출되고 있다.

  • Cinemachine 카메라가와 UI가 모두 LateUpdate에서 작동하기 때문에 순서를 보장할 수 없다.
  • 순서가 어긋남 → 스크린 좌표 계산이 “옛날 카메라 위치” 기준

 

확실한 해결법: Coroutine에서 WaitForEndOfFrame() 사용하기

IEnumerator FollowTarget()
{
    while (true)
    {
        yield return new WaitForEndOfFrame(); // 카메라 움직임 끝난 후 실행

        Vector3 screenPos = Camera.main.WorldToScreenPoint(target.position + offset);
        uiElement.position = screenPos;
    }
}

▶ 왜 이게 확실하냐?

  • WaitForEndOfFrame()은 모든 LateUpdate, 렌더링까지 끝난 뒤 실행됨
  • 카메라가 따라온 다음에 계산되므로, 튀는 일이 거의 없어짐