본문 바로가기

유니티(Unity)

비동기 함수 사용시 UI업데이트

비동기 함수에서는 UI업데이트가 안된다. 다른 스레드에서 작동되기 때문이다.(Unity는 일반적으로 메인스레드만 사용한다.)

private IEnumerator UpdateState()
    {
        WaitForSeconds delay = new WaitForSeconds(1.5f);
        while (true)
        {
            if (notifyType == 1)//계정 생성 성공
            {
                notifyText.text = "Create account success";
                notifyType = 0;
                Invoke("ClearNotifyText", 5f);
            }
            else if (notifyType == 10)//로그인 성공
            {
                notifyText.text = "Log in success";
                notifyType = 0;
                Invoke("ClearNotifyText", 5f);
            }
            else if (notifyType == 11)//로그인 중 오류가 발생했을 경우
            {
                notifyText.text = "Please verify your email or password again";
                notifyType = 0;
                Invoke("ClearNotifyText", 5f);
            }
            else if (notifyType == 12)//로그인 안했을 시
            {
                notifyText.text = "Please log in";
                notifyType = 0;
                Invoke("ClearNotifyText", 5f);
            }

            else if (notifyType == 100)
            {
                notifyText.text = "Error occurred. Please try again later";
                notifyType = 0;
                Invoke("ClearNotifyText", 5f);
            }
            else if (notifyType == 200)//이메일 인증 안했을 시
            {
                notifyText.text = "Please complete email verification";
                notifyType = 0;
                Invoke("ClearNotifyText", 5f);
            }
            yield return delay;
        }
    }

비동기 함수 안에 notifyType이라는 bool 형태의 멤버 변수에 값을 할당하고, 코루틴에서 이를 감지하여 ui를 업데이트 한다. 이와 비슷하게 이벤트로 동작시키려고도 해봤지만 결국 다른 스레드에서 작동한다. 물론 경우에 따라 다르겠지만 웬만하면 코루틴을 사용하면 간단하다.

'유니티(Unity)' 카테고리의 다른 글

uwp앱에서 exe파일 실행시키기  (0) 2023.08.23
unity firebase crash발생  (0) 2023.06.19
Firebase Storage MetaShop  (0) 2023.05.30
MetaShopEditor  (0) 2023.05.30
비동기 예시  (0) 2023.05.29