Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

짱이 될거야

Unity 2D Fade In/Out 본문

프로젝트

Unity 2D Fade In/Out

jeong57 2022. 10. 28. 13:27

Fade Out (기본 화면 -> Black)

1.     2D Canvas 생성

2.     Canvas > UI > Image(name: ‘Black’) 생성 후 stretchcanvas에 꽉 차도록 설정

  • Anchors를 화면을 조금 벗어나도록 설정해준다. (혹시 화면에 꽉 찰 때 빈 틈이 생길까봐)
  • 이미지 색을 검은색으로 변경

Black Image Inspector

3.     이미지 alpha 값을 0으로 하고 비활성화

4.     Assets/Scripts 폴더 생성 후 FadeScript.cs 작성 -> Canvas에 삽입

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class FadeScript : MonoBehaviour
{
    public Image Panel;
    float time = 0f;
    float F_time = 1f;

    public void Fade()
    {
        StartCoroutine(FadeFlow());
    }
    IEnumerator FadeFlow()
    {
        Panel.gameObject.SetActive(true);
        Color alpha = Panel.color;
        while (alpha.a < 1f)
        {
            time += Time.deltaTime / F_time;
            alpha.a = Mathf.Lerp(0, 1, time);
            Panel.color = alpha;
            yield return null;
        }
        yield return null;
    }
}

Canvas Inspector: FadeScript Panel 변수에 Black 이미지 할당

5.     Canvas > UI > Button 생성

6.     ButtonOn Click () 이벤트에 FadeScriptFade 함수 넣어준다.

Button의 On Click() 이벤트

7.   Canvasscript ‘Panel’ 변수에 ‘Black’ 컴포넌트 drag & drop

8.   만약 시작하자마자 fade out하고 싶다면, ScriptStart 함수에 Fade() 함수를 넣으면 된다.

 

 

 

Fade In (Black -> 기본 화면)

Button 누르면 Fade Out 되고, 1초 뒤에 바로 Fade In 실행되는 코드.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class FadeScript : MonoBehaviour
{
    public Image Panel;
    float time = 0f;
    float F_time = 1f;

    public void Fade()
    {
        StartCoroutine(FadeFlow());
    }
    IEnumerator FadeFlow()
    {
        Panel.gameObject.SetActive(true);
        time = 0f;
        Color alpha = Panel.color;        
        while (alpha.a < 1f)
        {
            time += Time.deltaTime / F_time;
            alpha.a = Mathf.Lerp(0, 1, time);
            Panel.color = alpha;
            yield return null;
        }

        time = 0f;

        yield return new WaitForSeconds(1f);

        while (alpha.a > 0f)
        {
            time += Time.deltaTime / F_time;
            alpha.a = Mathf.Lerp(1, 0, time);
            Panel.color = alpha;
            yield return null;
        }
        Panel.gameObject.SetActive(false);
        yield return null;
    }
}

 

참고

https://www.youtube.com/watch?v=NYdLInZVsAM 

 

Comments