fgm24/Assets/Scripts/UI/Wait2SecondsToShow.cs

48 lines
1.2 KiB
C#

using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class Wait2SecondsToShow : MonoBehaviour
{
// Reference to the Image component
private Image canvas;
private void Start()
{
canvas = GetComponent<Image>();
Invoke(nameof(StartFade), 2.8f);
}
void StartFade()
{
canvas.enabled = true;
StartCoroutine(FadeOut(2f));
}
// Coroutine to fade out the image
public IEnumerator FadeOut(float duration)
{
// Make sure the canvas is not null
if (canvas == null)
{
yield break; // Exit if canvas is not assigned
}
// Starting alpha value (1 is fully opaque)
float startAlpha = 1.0f;
// Elapsed time
float time = 0;
while (time < duration)
{
time += Time.deltaTime; // Update the time based on the time passed since last frame
float alpha = Mathf.Lerp(startAlpha, 0, time / duration); // Calculate the new alpha value
canvas.color = new Color(canvas.color.r, canvas.color.g, canvas.color.b, alpha); // Apply the new alpha value to the canvas color
yield return null; // Wait for the next frame
}
Destroy(gameObject);
}
}