近期學習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
,可對速度調整。