57 lines
1.3 KiB
C#
57 lines
1.3 KiB
C#
using UnityEngine;
|
||
using UnityEngine.UI;
|
||
using System.Collections;
|
||
|
||
public class FadeToBlack : MonoBehaviour
|
||
{
|
||
public float fadeDuration = 1.5f; // 渐变时间
|
||
private Image blackImage;
|
||
public GameObject LightLinp;//灯光
|
||
|
||
void Start()
|
||
{
|
||
blackImage = GetComponent<Image>();
|
||
|
||
}
|
||
|
||
// 外部调用:渐变变黑
|
||
public void StartFade()
|
||
{
|
||
LightLinp.SetActive(false);
|
||
StartCoroutine(FadeToBlackCoroutine());
|
||
}
|
||
|
||
// 外部调用:直接变黑
|
||
public void InstantBlack()
|
||
{
|
||
blackImage.color = new Color(0, 0, 0, 1f); // 设置为全黑
|
||
}
|
||
|
||
public void ReturnWhite()
|
||
{
|
||
LightLinp.SetActive(true);
|
||
blackImage.color = new Color(0, 0, 0, 0f); // 设置为全白
|
||
}
|
||
|
||
|
||
// 协程:控制渐变过程
|
||
private IEnumerator FadeToBlackCoroutine()
|
||
{
|
||
float elapsedTime = 0f;
|
||
|
||
// 目标透明度
|
||
float targetAlpha = 0.6f;
|
||
|
||
while (elapsedTime < fadeDuration)
|
||
{
|
||
elapsedTime += Time.deltaTime;
|
||
// 计算当前透明度(从0逐渐到目标透明度0.6)
|
||
float alpha = Mathf.Lerp(0f, targetAlpha, elapsedTime / fadeDuration);
|
||
blackImage.color = new Color(0, 0, 0, alpha);
|
||
yield return null; // 等待下一帧
|
||
}
|
||
|
||
// 确保最终达到目标透明度
|
||
blackImage.color = new Color(0, 0, 0, targetAlpha);
|
||
}
|
||
} |