C#, Unity

C#, Unity) IEnumerator, Coroutine, Lerp 함수

나무늘보섬 2024. 8. 12. 19:43
  • IEnumerator, StartCoroutine
    • 2개는 묶어서 생각하면 편함
    • 프레임과 프레임 사이에 함수를 호출, 원래 진행하던 함수를 멈추고, StartCoroutine을 사용하여 새로운 함수 호출
    • 대부분 StartCoroutine 혹은 StopCoroutine이 함께 사용됨.
    • yield return을 통해 프레임 delay나 몇 초간의 delay작동 후, 원함수로 넘어갈 수 있음

    

               - ex) 보스 몹이 죽을 떄, Destroy를 바로 하는 것이 아니라 중간에 StartCoroutine을 사용하여 IEnumerator로                              선언 된 함수를 호출하여 함수 안의 내용 실행 후, 보스몹 Destroy를 진행

               - ex) fadeIn, fadeOut 될 때 사용


Mathf.Lerp (float a, float b, float t)

  • Lerp 함수: Linear Interpolation
  • a와 b값을 선형보간(?)을 이용하여 직선을 긋고, 값을 계산 / t는 원하는 비율로서 조정 가능
  • 프레임마다 움직임을 부드럽게 하기 위해서 사용되는 함수
  • 반환값 ->   a+(b-a) *t

 


 IEnumerator, Coroutine, Lerp 예시 코드 

(코드 출처: team Cheese -> 팀 개발 코드)

 

더보기

 

if (parameters == true)

    StartCoroutine(Afunc());

 

IEnumerator Afunc()

{

// Few Contidions && Codes

yield return StartCoroutine(FadeOut());

 

// Few Contidions && Codes

yield return StartCoroutine(FadeIn());

}

 

 IEnumerator FadeIn()
    {
        fadeImage.gameObject.SetActive(true);
        fadeImage.color = Color.black;

        float timer = 0f;
        while (timer < fadeDuration)
        {
            timer += Time.deltaTime;
            fadeImage.color = Color.Lerp(Color.black, Color.clear, timer / fadeDuration);
            yield return null;
        }

        fadeImage.gameObject.SetActive(false);
    }

    IEnumerator FadeOut()
    {
        fadeImage.gameObject.SetActive(true);
        fadeImage.color = Color.clear;

        float timer = 0f;
        while (timer < fadeDuration)
        {
            timer += Time.deltaTime;
            fadeImage.color = Color.Lerp(Color.clear, Color.black, timer / fadeDuration);
            yield return null;
        }

        fadeImage.color = Color.black;
    }

 

 


 

참고 자료

https://www.youtube.com/watch?v=CU1GHT9tHqQ&list=PLV08tNO3dHvdBRSMHjElHNYXUZvumCJ1G&index=7