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?
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.
Just lerp the alpha of the object over a set time period. Then destroy (or return to object pool) as needed.