Sprite Renderer Control Opacity

Hello all… Im trying to find out how to control the opacity of an object… here is my script:

using UnityEngine;
using System.Collections;

public class RainDestroy : MonoBehaviour
public float deathTime;

void Update () 
	Destroy (gameObject, deathTime);


I am accessing a variable with a time value… How do i overtime… control the Sprite renderer to fade the object into zero opacity??


You can use a Coroutine for this…

IEnumerator FadeAndDestroy()
  float timer = 0;
  while (timer <= 1.0f)
    timer += Time.deltaTime;
    // TODO : set your renderer color to new Color(1, 1, 1, 1.0f - timer)...
    // the last value is alpha and this will change it from 1 to 0 over 1 second
    yield return null;       // wait for next frame


When you’re ready to destroy the object, kick off the coroutine…


You’ll need to tweak some things to make sure the coroutine has a reference to the game object, and if you want a delay longer than 1 second you’ll need to scale the alpha value in the color so it goes from 1 to 0 over the course of n seconds. I’ll leave that as an exercise for the reader.