Pavel Nakonechnyy

Unity | 2D Color Fade

Published by Pavel Nakonechnyy on (updated: ) in GameDev. Tags: .

Small script, that can be used to make color transition in given time. Can be used only for SpriteRenderer.

using System;
using UnityEngine;

public class FadeExt {
        public static IEnumerator Fade(GameObject obj, Color startcolor, Color endcolor,
 float time, SpriteRenderer renderer = null, float tick = 0.01f) {
            renderer = renderer ?? obj.GetComponent();
            var lespspeed = tick / time;

            renderer.color = startcolor;

            while (renderer.color != endcolor) {
                renderer.color = Color.Lerp(renderer.color, endcolor, lespspeed);

                yield return new WaitForSeconds(tick);
            }
        }
    }
327