44 lines
1016 B
C#
44 lines
1016 B
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
using System.Collections;
|
|
|
|
public class FadeToBlack : MonoBehaviour
|
|
{
|
|
public float fadeDuration = 1.5f; // 渐变时间
|
|
private Image blackImage;
|
|
|
|
void Start()
|
|
{
|
|
blackImage = GetComponent<Image>();
|
|
|
|
}
|
|
|
|
// 外部调用:渐变变黑
|
|
public void StartFade()
|
|
{
|
|
StartCoroutine(FadeToBlackCoroutine());
|
|
}
|
|
|
|
// 外部调用:直接变黑
|
|
public void InstantBlack()
|
|
{
|
|
blackImage.color = new Color(0, 0, 0, 1f); // 设置为全黑
|
|
}
|
|
|
|
// 协程:控制渐变过程
|
|
private IEnumerator FadeToBlackCoroutine()
|
|
{
|
|
float elapsedTime = 0f;
|
|
|
|
while (elapsedTime < fadeDuration)
|
|
{
|
|
elapsedTime += Time.deltaTime;
|
|
float alpha = Mathf.Clamp01(elapsedTime / fadeDuration); // 计算透明度
|
|
blackImage.color = new Color(0, 0, 0, alpha);
|
|
yield return null; // 等待下一帧
|
|
}
|
|
|
|
// 确保最终完全变黑
|
|
blackImage.color = new Color(0, 0, 0, 0.6f);
|
|
}
|
|
} |