예지의 개발 로그포스 (Yeji's Log Force)

[Unity] fade out 퀄리티 개선 본문

[Unity] Projects & Study/Loop - Interactive Movie

[Unity] fade out 퀄리티 개선

Yeji Heo 2023. 2. 5. 10:44

지금껏 fade In/Out 효과를 쓸 일이 굉장히 많았는데, 이전 프로젝트까지는 늘 그저 time을 통해서 alpha값을 빼주는 코드로 구현했었다.

이번에는 문득 이 효과가 뚝뚝 끊기면서 밝아지거나 어두워지는, 조금은 부자연스럽다는 느낌이 들었다.

어떻게 하면 더 자연스럽게 구현할지 고민하다가, 예전에 Vector값을 옮길때 부드럽게 하기 위해서 Lerp함수를 썼던 것이 생각나서, Color도 Lerp함수가 제공되는지 찾아보니 예상대로 존재했다!

Color.Lerp()를 이용하니 체감상 훨씬 자연스러운 Fade In/Out효과를 구현할 수 있었던 것 같다.

 

  • 기존 코드
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Fade : MonoBehaviour
{
    public float time;
    public float fades;

    void Start()
    {
        fades = 1.0f;
    }

    private void Update()
    {
        if (this.GetComponent<Image>().color.a > 0.0f)
        {
            time += Time.deltaTime;
            if (fades > 0.0f && time >= 0.1f)
            {
                fades -= 0.1f;
                this.GetComponent<Image>().color =  new Color(0, 0, 0, fades);
                time = 0;
            }
        }
        else this.gameObject.SetActive(false);
    }
}

 

  • 수정한 코드
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Fade : MonoBehaviour
{
    float duration = 1;
    float smoothness = 0.02f;

    void Start()
    {
        StartCoroutine("LerpColor");
    }

    IEnumerator LerpColor()
    {
        float progress = 0; 
        float increment = smoothness / duration; 
        while (progress < 1)
        {
            this.GetComponent<Image>().color = Color.Lerp(Color.black, Color.clear, progress);
            progress += increment;
            yield return new WaitForSeconds(smoothness);
        }
        this.gameObject.SetActive(false);
    }
}

 

참고

https://redccoma.tistory.com/145

Comments