- Home /
Edit Keyframe of Animation Curve
I have an Animation Curve defined in the inspector for some float interpolation, and I'd like to then edit some of the Keyframe's properties at runtime. However, something like
Curve1.keys[0].time = 5f;
seems to do nothing to affect the Keyframe. The best I can do is copy the Keyframe array, adjust it separately, and then reassign it back to the Curve. Am I missing something that would let me edit the variables as I need them?
Thanks!
Add$$anonymous$$eyframe() should honestly have a bool parameter to allow (or disallow) overwriting the keyframe with the same time. Its stupid to have to jump through hoops to do something so simple.
Answer by JonathanCzeck · Dec 05, 2015 at 09:14 PM
The reason that does not work is because Keyframe is a struct, a value type. In UnityScript aka JavaScript they do work behind the scenes so it works. In C# you do it manually:
KeyFrame[] keys = Curve1.keys; // Know that this is making a copy of all keys
Keyframe keyFrame = keys[0];
keyFrame.time = 5f;
keys[0] = keyframe;
Curve1.keys = keys; // This is copying the keys back into the AnimationCurve's array.
(Untested)
There's no need to copy a keyframe into a local variable. You can access struct members fine inside an array. The problem is the property which returns a copy of the internally used array. The actual array sits on the native code side. Whenever you "read" the keys property a managed array is created and filled with the keyframes. You have to call the setter of the keys property to apply the changes. So this is enough:
$$anonymous$$eyFrame[] keys = Curve1.keys; // Get a copy of the array
keys[0].time = 5f;
Curve1.keys = keys; // assign the array back to the property
For things like that it would be better if UT would remove properties like that and provide Get and Set methods since that would be more intuitive. It's the same with the $$anonymous$$esh class.
Yeah, I had arrived at the same conclusion. For the moment I can write my own Set() for Curves and go from there.