Deep copy AnimationCurve

I am trying to duplicate an animation curve but it is creating references to the original curve instead. I want a new, independent curve.

My code:

creating the values

 var thighCurve : AnimationCurve;
var calfCurve : AnimationCurve;
var footCurve : AnimationCurve;

var thighCurveR : AnimationCurve;
var calfCurveR : AnimationCurve;
var footCurveR : AnimationCurve;

Copying them in Start()

thighCurveR = thighCurve;
	calfCurveR = calfCurve;
	footCurveR = footCurve;

AnimationCurve is an Object, not a primitive type, so it’s assigned by reference, not by value (what you would call copying).

Read this: Value vs Reference Types in C# (it’s in C# but the same principals apply regardless of language)

In order to copy the primitive values inside the thighCurve AnimationCurve object, you’ll need to create a new AnimationCurve then loop through all of the keys and copy their values one by one.

Another one way to make a deep copy is to serialize this to bytes array and restore (deserialize) it as new object. If I remember correctly there are about 4 basic techniques for making deep copy, but serializing the most convinient for data persistence, though it also requred more resouces the others.

Since trying to grab keys from an Animation curve returns a copy, Can’t you just
curveA = new Animationcurve(curveB.keys);
No need to loop, deserialise, etc

2 Likes

Yes, creating new instance via constructor also one of these 4 technoques, it is easiest way, but it works correctly only when whole object (include internal state) could be initialised via constructor.
You can read more about deep copying in this blog Deep Copy | 2,000 Things You Should Know About C#

Thank you !