Color Gradients

Hi all,

How would I go about implementing a color gradient that changes color depending on my float, the float can be -50.0 to 50.0.

The following code does change the color (first key only as an example) but you will not see any changes in the gradient’s property drawer because it seems Unity won’t update the gradient’s preview when you change its values from code. Nonetheless you can check, by opening up the gradient editor, that under the hood the color is actually being set so the code grad.Evaluate(0f); will return your current color.

using UnityEngine;
using System.Collections;

public class GradientTest : MonoBehaviour {

    public Gradient grad;
    public float value = 0f;

    public Color vColor = Color.white;

    GradientColorKey[] gCKeys;
    GradientAlphaKey[] gAKeys;

    void Update()
        // Debug.Log(grad.Evaluate(0f)); // Uncomment to verify that color does change.

	public void updateGradient () {

        gCKeys = grad.colorKeys; // store color keys
        gAKeys = grad.alphaKeys; // store alpha keys

        float nValue = value / 100f + 0.5f; // normalize that variable going from -50 to 50
        gCKeys[0].color.r = nValue; // make color vary with any formula here.
        gCKeys[0].color.g = nValue;
        gCKeys[0].color.b = nValue;
        vColor = gCKeys[0].color; // just to see the color in the Inspector

        grad.SetKeys(gCKeys, gAKeys); // set color and alpha keys

Note: Neither doing a custom editor and force Repaint will achieve gradient preview update.