Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Deep copy AnimationCurve

Discussion in 'Scripting' started by spendew, May 13, 2014.

  1. spendew

    spendew

    Joined:
    Feb 12, 2012
    Posts:
    104
    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
    Code (csharp):
    1.  var thighCurve : AnimationCurve;
    2. var calfCurve : AnimationCurve;
    3. var footCurve : AnimationCurve;
    4.  
    5. var thighCurveR : AnimationCurve;
    6. var calfCurveR : AnimationCurve;
    7. var footCurveR : AnimationCurve;
    Copying them in Start()
    Code (csharp):
    1. thighCurveR = thighCurve;
    2.     calfCurveR = calfCurve;
    3.     footCurveR = footCurve;
     
  2. Cameron_SM

    Cameron_SM

    Joined:
    Jun 1, 2009
    Posts:
    915
    AnimationCurve is an Object, not a primitive type, so it's assigned by reference, not by value (what you would call copying).

    Read this: http://www.albahari.com/valuevsreftypes.aspx (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.
     
  3. Patico

    Patico

    Joined:
    May 21, 2013
    Posts:
    886
    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.
     
  4. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    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
     
    wpetillo and kaleidosgu like this.
  5. Patico

    Patico

    Joined:
    May 21, 2013
    Posts:
    886
    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 http://csharp.2000things.com/tag/deep-copy/
     
  6. florinel2102

    florinel2102

    Joined:
    May 21, 2019
    Posts:
    75
    Thank you !