Adding an animation curve for SpriteRenderer.color via code.

I’m trying to write a script which adds an animation curve animating the color property of a SpriteRenderer.

I changed the example from the Unity Script Reference to this:

using UnityEngine;

[RequireComponent(typeof(Animation))]
[RequireComponent(typeof(SpriteRenderer))]
public class Example : MonoBehaviour
{
    void Start()
    {
        AnimationCurve curve = AnimationCurve.Linear(0, 0, 2, 1);
        AnimationClip clip = new AnimationClip();
        clip.SetCurve("", typeof(SpriteRenderer), "color.r", curve);
        clip.SetCurve("", typeof(SpriteRenderer), "color.g", curve);
        clip.SetCurve("", typeof(SpriteRenderer), "color.b", curve);
        clip.SetCurve("", typeof(SpriteRenderer), "color.a", curve);
        animation.AddClip(clip, "test");
        animation.Play("test");
    }
}

I also added an animation curve by hand to see if you can actually animate that property (after the script executed).

26745-anim_window.png

(Top: Added by script, Bottom: Added by hand)

They seem to be identical, but as you can see the one added by the script is displayed in red. It doesn’t affect the color in any way. (I guess it doesn’t find the property)

Is there anything I’m doing wrong?

Cheers!

It’s been months since I looked into this in detail, but in order to animate the color property of a renderer you have to use m_Color.r (etc):

 using UnityEngine;
 
[RequireComponent(typeof(Animation))]
[RequireComponent(typeof(SpriteRenderer))]
public class Example : MonoBehaviour
{
    void Start()
    {
        AnimationCurve curve = AnimationCurve.Linear(0, 0, 2, 1);
        AnimationClip clip = new AnimationClip();
        clip.SetCurve("", typeof(SpriteRenderer), "m_Color.r", curve);
        clip.SetCurve("", typeof(SpriteRenderer), "m_Color.g", curve);
        clip.SetCurve("", typeof(SpriteRenderer), "m_Color.b", curve);
        clip.SetCurve("", typeof(SpriteRenderer), "m_Color.a", curve);
        animation.AddClip(clip, "test");
        animation.Play("test");
    }
}