近期学习unity3d,网上找到的教程大都为unity5.x,而个人使用的是2019,因此许多细节有所变化
首先是跟着某视频教程学习渐隐渐现画面的实现时,发现按部就班地编码无法实现该功能
搜索许久后发现在新版中应按如下操作:
- 创建
Scripts
文件夹,并创建C#脚本;同时,在Hierarchy
中创建一个Game Object(Create empty
), 均命名为FadeInOut
- 编写
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");
}
}
}
- 点击
Hierarchy
中的FadeInOut
对象,在Inspector
中的Transform
标签,点击右上角的齿轮reset座标;
后add component
添加一个GUI Texture
,随意保存一个黑色背景的图像,将其拖拽到texture
中,Color
可自己根据图像背景选择合适的颜色;
后拖拽编写的FadeInOut
脚本文件至Inspector
- 点击
Hierarchy
中的Main Camera
,点击add component
, 添加一个GUI layer
,并勾选
如此,即实现初始画面的渐隐渐现,调整fade speed
,可对速度调整。