- Home /
Slowly dissapearing objects in Unity3D
Hello, I've been trying to make a game, in which there are a lot of fallig objects that stay on the ground. I want to delete them. I could use Destroy(), but then the obect just dissapears and it doesn't look really good. Is there a way I could make the objects dissapear slowly, so they would become more transparent in a given amount of time?
Answer by JP_Ferreira · Jan 10, 2018 at 04:43 PM
Hi @PlatPlayz.
Here you go the function to fade:
IEnumerator FadeOutAndDestroy(float time )
{
float elapsedTime = 0;
Color startingColor = transform.GetComponent<Renderer>().material.color;
Color finalColor = new Color(startingColor.r, startingColor.g, startingColor.b, 0);
while (elapsedTime < time)
{
transform.GetComponent<Renderer>().material.color = Color.Lerp(startingColor, finalColor, (elapsedTime / time));
elapsedTime += Time.deltaTime;
yield return null;
}
Destroy(gameObject);
}
And you call this method with:
StartCoroutine(FadeOutAndDestroy(5));
5 is the seconds to fade out if you want to change the values just make a variable and/or change the value.
NOTE: The material you assign to the object must have the rendering mode in FADE, otherwise it will not work.
Thank you very much, your script works perfectly, but when I set the rendering mode to fade, I can see through it a little bit. Is there a way to overcome that?
You could use a opaque material at start and change it to a fade material in the coroutine (right before fading out).
Faint? did you mean Fade?... Is awkward because if i have my alpha at 255 the object is fully opaque. You have to set the initial alpha to be 1 (via script) or to be 255 (via editor).
You are right, I meant Fade, sorry. i've already edited the comment. But I'm not sure where I can find where to set the alpha.
Answer by creganjordan292 · Jan 10, 2018 at 02:46 PM
Just lerp the alpha of the object over a set time period. Then destroy (or return to object pool) as needed.