I guess something like this, I would not recommend this structure. Maybe use a tween library or create your own, for easier aborting and stuff. Note I did not test this, but it should work.
static bool StopShowAmmoText;
static IEnumerator show_ammo_text(int ammo)
{
// Stop the other called enumerators and wait one frame
StopShowAmmoText = true;
yield return null;
StopShowAmmoText = false;
// Settings
const float WaitTime = 1.0f;
const float ShowTime = 0.5f;
const int Increments = 10;
Color newColor = new Color(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value, 1f);
// Apply the text and color
ammo_text.enabled = true;
ammo_text.color = newColor;
ammo_text.text = "AMMO LEFT ~ " + ammo;
// Keep doing this wile the time this function is running is lower than (WaitTime + ShowTime)
float time = 0.0f;
while (time < (WaitTime + ShowTime))
{
// Raise the time
time += Time.deltaTime;
// Wait for WaitTime amount of second
if (time < WaitTime)
{
// Keep checking if we need to stop
if (StopShowAmmoText) { yield break; }
yield return null;
continue;
}
// Calculate the new color
float t = 1.0f - Mathf.InverseLerp(WaitTime, (WaitTime + ShowTime), time);
newColor.a = Mathf.Round(t * Increments) / Increments; // This one uses increments
// newColor.a = t; // Use this one for fully smooth
ammo_text.color = newColor;
// Check if we need to stop
if (StopShowAmmoText) { yield break; }
yield return null;
}
// We finished so disable the text
ammo_text.enabled = false;
}
↧