Hello all, i am having an issue creating a Fade
I’ve attached CanvasGroup to stamina bar, script is below and video presentation.
problem is: it snaps to value 0 or 1 , it doesnt fade over fadeDuration seconds
VIDEO LINK
SCRIPT:
using TMPro;
using UnityEngine;
using System.Collections;
public class staminafade : MonoBehaviour
{
public CanvasGroup staminaCanvasGroup;
public _PlayerController player;
public float fadeDuration;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
player = FindFirstObjectByType<_PlayerController>();
}
// Update is called once per frame
void Update()
{
if(player.currentStamina > 95)
{
StartCoroutine(Fade(1f, 0f, fadeDuration));
} else if(player.currentStamina < 94)
{
StartCoroutine(Fade(0f, 1f, fadeDuration));
}
}
public IEnumerator Fade(float startAlpha, float endAlpha, float duration)
{
float elapsedTime = 0f;
while (elapsedTime < duration)
{
elapsedTime += Time.deltaTime;
float newAlpha = Mathf.Lerp(startAlpha, endAlpha, elapsedTime / duration);
staminaCanvasGroup.alpha = newAlpha; // Update CanvasGroup alpha
yield return null; // Wait until the next frame
}
staminaCanvasGroup.alpha = endAlpha; // Ensure exact endAlpha is set
}
}