unity2019 實現畫面漸隱漸現

近期學習unity3d,網上找到的教程大都爲unity5.x,而個人使用的是2019,因此許多細節有所變化
首先是跟着某視頻教程學習漸隱漸現畫面的實現時,發現按部就班地編碼無法實現該功能
搜索許久後發現在新版中應按如下操作:

  1. 創建Scripts文件夾,並創建C#腳本;同時,在Hierarchy中創建一個Game Object(Create empty), 均命名爲FadeInOut
    在這裏插入圖片描述
  2. 編寫FadeInOut的C#腳本文件,代碼如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class FadeInOut : MonoBehaviour
{
    public float fadeSpeed = 1.5f; // 漸隱漸現速率
    private bool sceneStarting = true; // 表示場景是否開始,若開始,需要有濺現效果
    private GUITexture tex;

    void Start()
    {
        tex = this.GetComponent<GUITexture>();
        tex.pixelInset = new Rect(0, 0, Screen.width, Screen.height);
    }


    // Lerp函數在update中調用
    void Update()
    {
        if (sceneStarting)
        {
            StartScene();
        }
    }
    // 漸隱
    private void FadeToClear()
    {
        tex.color = Color.Lerp(tex.color, Color.clear, fadeSpeed * Time.deltaTime);
    }

    // 濺現
    private void FadeToBlack()
    {
        tex.color = Color.Lerp(tex.color, Color.black, fadeSpeed * Time.deltaTime);
    }

    // 開始濺現,結束漸隱
    private void StartScene()
    {
        FadeToClear();
        // alpha 通道小於等於0.5
        if (tex.color.a <= 0.05f)
        {
            tex.color = Color.clear;
            tex.enabled = false;
            sceneStarting = false;
        }
    }

    public void EndScene()
    {
        tex.enabled = true;
        FadeToBlack();
        if (tex.color.a >= 0.95f)
        {
            SceneManager.LoadScene("SampleScene");
        }
    }
}
  1. 點擊Hierarchy中的FadeInOut對象,在Inspector中的Transform標籤,點擊右上角的齒輪reset座標;
    add component添加一個GUI Texture,隨意保存一個黑色背景的圖像,將其拖拽到texture中,Color可自己根據圖像背景選擇合適的顏色;
    後拖拽編寫的FadeInOut腳本文件至Inspector
    在這裏插入圖片描述
  2. 點擊Hierarchy中的Main Camera,點擊add component, 添加一個GUI layer,並勾選
  3. 在這裏插入圖片描述
    如此,即實現初始畫面的漸隱漸現,調整fade speed,可對速度調整。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章