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,可对速度调整。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章