hi i want to make a object fade out over a unspecified amount of time i dont know how to do that i know it is with (time.deltatime) but i dont know to write it can someone help me with this?
I’ll give you a little piece of code I’ve used for years to make transitions like this really straightforward.
IEnumerator DoAThingOverTime(Color start, Color end, float duration) {
for (float t=0f;t<duration;t+=Time.deltaTime) {
float normalizedTime = t/duration;
//right here, you can now use normalizedTime as the third parameter in any Lerp from start to end
someColorValue = Color.Lerp(start, end, normalizedTime);
yield return null;
}
someColorValue = end; //without this, the value will end at something like 0.9992367
}
You can simply call StartCoroutine(DoAThingOverTime(x,y,1f) ); and it’ll handle the transition.
Does that help?
thx this is what i was searching for ![]()
Sorry for opening again this thread … I am a noob … I can’t understand the:
someColorValue = Color.Lerp(start, end, normalizedTime);
part. What I have to do with “SomeColorValue”? Of course It’s giving me an error!
The person who posted that code didn’t make any assumptions over exactly how the color would be used. So, the code just shows how to transition from one color to another color over time. It’s assumed that upon every calculation of someColorValue, the color would be assigned to some visible object. For example, to the color of a sprite, or the color of a material.
Anyway, this code just produces a color. Assign that color to the color property of whatever thing you’re trying to change the color of.
To specifically address the “error” you’re getting, just put var or Color in front of someColorValue. The original code didn’t bother to declare it, because often you won’t be storing the value in a variable, you’d be assigning it directly to a color property of an object.
Thanks Dgoyette!
What I am trying to achieve is turning my attached gameobject from solid (255 alpha, I guess) to transparent (0 alpha I guess), before destroying it
public float durata = 1f;
private Color x, y;
Color someColorValue;
void Start() {
x.a = 255f;
y.a = 0f;
}
void FixedUpdate () {
StartCoroutine(DoAThingOverTime(x, y, 1f));
}
public void EliminaScoreggia () {
Destroy(gameObject);
}
public IEnumerator FadeOut (float dur) {
for (float f = 1f; f >= -0.05f; f -= 0.05f) {
Color color = rend.material.color;
color.a = f;
rend.material.color = color;
yield return new WaitForSeconds(0.05f);
}
}
IEnumerator DoAThingOverTime(Color start, Color end, float duration)
{
for (float t = 0f; t < duration; t += Time.deltaTime)
{
float normalizedTime = t / duration;
//right here, you can now use normalizedTime as the third parameter in any Lerp from start to end
someColorValue = Color.Lerp(start, end, normalizedTime);
yield return null;
}
someColorValue = end; //without this, the value will end at something like 0.9992367
}
Using this code … I can’t see no effect on my Gameobject! ;-\
That depends on the material and what shader it’s using. Some materials support transparency, while others don’t. So in general it’s pretty difficult to come up with a “works for everything” solution without knowing what material(s) you’re using on your objects.
However, if it’s for UI objects, then there’s an even simpler solution: Just add a CanvasGroup to your parent UI gameobject. That exposes an alpha value that you can lerp between 0 and 1 to fade it in/out.
And you’ve confirmed that the material supports transparency? What shader are you using? If you manually adjust the material color’s alpha in the Inspector, does it look the way you’d expect?
Hey!
Thanks for your support! I mixed together two tutorials and I found the right recipe for my needing!
IEnumerator DoAThingOverTime(float duration)
{
for (float t = 0f; t < duration; t += Time.deltaTime)
{
Color c = rend.material.color;
c.a = c.a - 0.0001f;
rend.material.color = c;
yield return null;
}
Uhm, but now I have a new (of course!) problem
I want to destroy object when Alpha is 0 but:
if (c.a.Equals(0f)) {
Debug.Log("Alpha is 0");
}
Does not work! :-\ Any Idea?
Checking for exact equality in this kind of situation can be an issue. Your alpha value is probably ending up either below zero, or some tiny fraction away from zero. It’s also possible that floating point inaccuracy is prevent exactly equality.
I’d check whether the value is <= some small amount instead of checking equality with zero.
Hey! Thanks Again! Well My goal is REALLY stupid (fade away a “fart cloud”) ![]()
I did it like this:
IEnumerator DoAThingOverTime(float duration)
{
for (float t = 0f; t < duration; t += Time.deltaTime)
{
Color c = rend.material.color;
Color fine = rend.material.color;
c.a = c.a - 0.0005f;
rend.material.color = c;
yield return null;
if (rend.material.color.a <= 0f)
{
EliminaScoreggia();
}
}
}
IEnumerator DoAThingOverTime(float duration)
{
for (float t = 0f; t < duration; t += Time.deltaTime)
{
Color c = rend.material.color;
Color fine = rend.material.color;
c.a = c.a - 0.0005f;
rend.material.color = c;
yield return null;
if (rend.material.color.a <= 0f)
{
EliminaScoreggia();
}
}
}
This is a necro-post, but for anyone looking for the answer in the future, here’s how you do it.
What you’re trying to accomplish is a basic D = RT equation. You need to know how far apart your color vectors are from the target, since the values can be negative or positive. It’s kind of confusing at first, but it’s actually pretty simple. I whipped this up kinda quick for my current project, so the variable names may be confusing, but the equation still applies.
I used fixedTime rather than deltaTime because I needed the equation to stay consistent. You could use deltaTime if you like, you would just need to adjust the function to update the equation per frame.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class UI_FadeInOut : MonoBehaviour
{
public Image targetImage;
public Color[] finalColor;
public float[] fadeTime;
void Start()
{
Fade(0);
}
IEnumerator FadeColor(int _pos)
{
Color changePerSecond = GetChangePerSecond(targetImage.color, finalColor[_pos], fadeTime[_pos]);
float time = 0;
Color col = targetImage.color;
while (targetImage.color != finalColor[_pos])
{
time += Time.fixedDeltaTime;
col = targetImage.color;
// Add the color change to the current color
col += changePerSecond * Time.fixedDeltaTime;
targetImage.color = col;
// Just to make sure we end our coroutine
if(time >= fadeTime[_pos])
{
targetImage.color = finalColor[_pos];
}
yield return new WaitForFixedUpdate();
}
Debug.Log("UI_FadeInOut :: COLOR FADE COMPLETE");
Fade(_pos == 0 ? 1 : 0);
}
Color GetChangePerSecond(Color _currentColor, Color _target, float _endTime)
{
Color myColor = _currentColor;
Color targColor = _target;
Color distance = targColor - myColor;
return distance/_endTime; // Returns the change needed per second
}
/// <summary>
/// Fade the image color to a position on its Color array.
/// </summary>
/// <param name="_fadePosition"></param>
public void Fade(int _fadePosition)
{
StartCoroutine(FadeColor(_fadePosition));
}
}
I’ll say it again: coroutines are NOT appropriate for fading in and out.
The reason is because they get into all kinds of weird edge cases if you somehow get two instances of the coroutine running at once and because they bring you zero value.
Fading, simple and easy:
I suppose it depends in what context you’re using it. In a situation where it is impossible for there to be a conflict (like in my game) then it’s perfectly usable. But, you are correct.
I haven’t had to use this, but would it not fix that issue if you use StopAllCoroutines(); before starting one?
pretty nice method name, btw ![]()