Search Unity

Load, modify and save animation with code

Discussion in 'Animation' started by kor6k, Jan 19, 2017.

  1. kor6k

    kor6k

    Joined:
    Jan 8, 2017
    Posts:
    50
    Hello,
    I have a lot of animation to do for my game so i created an animation generator.
    Here is the code:

    Code (CSharp):
    1. AnimationEvent[] aEvents = null;
    2. // Load the multitexture
    3. UnityEngine.Object[] textures  = Resources.LoadAll("my_spritesheet");
    4. int FrameNb = textures.Length - 1;
    5.  
    6. // Load the animation asset
    7. string asset_path = "Assets/Animations/my_anim.anim";
    8. AnimationClip animClip = (AnimationClip)AssetDatabase.LoadAssetAtPath(asset_path, typeof(AnimationClip));
    9.  
    10. animClip.name = "my_anim";
    11. animClip.frameRate = FrameNb;
    12. float time = 1f / FrameNb;
    13.  
    14. // create Editor Curve Binding
    15. EditorCurveBinding curveBinding = new EditorCurveBinding();
    16.  
    17. // put the typeof(SpriteRenderer) as the binding type.
    18. curveBinding.type = typeof(SpriteRenderer);
    19. // Regular path to the gameobject: empty string means root
    20. curveBinding.path = "";
    21. // property name to change the sprite of a sprite renderer
    22. curveBinding.propertyName = "m_Sprite";
    23.  
    24. // An array to hold the object keyframes
    25. ObjectReferenceKeyframe[] keyFrames = new ObjectReferenceKeyframe[FrameNb];
    26.  
    27. for (int i = 0; i < FrameNb; i++)
    28. {
    29.     keyFrames[i] = new ObjectReferenceKeyframe();
    30.     // set the time
    31.     keyFrames[i].time = i * time;
    32.     // set reference for the sprite you want
    33.     keyFrames[i].value = textures[i + 1];
    34.  
    35. }
    36.  
    37. // Create animation event
    38. aEvents = new AnimationEvent[1];
    39. aEvents[0] = new AnimationEvent();
    40. aEvents[0].functionName = "AttackEnd";
    41. aEvents[0].time = (FrameNb - 1) * time;
    42. animClip.events = aEvents;
    43.  
    44. AnimationUtility.SetObjectReferenceCurve(animClip, curveBinding, keyFrames);
    45.  
    46. animClip.EnsureQuaternionContinuity();
    47. AssetDatabase.SaveAssets();
    this code should load an anim from assets, load a multisheet texture, create the animation with the texture, add an animation event in the last frame of the animation and save the asset

    Everythings work fine except the animation event which is not added...
    Where is the error???
    Thanks in advance !
     
    zengsadi233 and Alien_Chen like this.
  2. kor6k

    kor6k

    Joined:
    Jan 8, 2017
    Posts:
    50
    I think I found the solution but I did not test it for now:
    I have to use:

    instead of animClip.events = aEvents;

    Can someone confirm?
     
    strexet likes this.
  3. kor6k

    kor6k

    Joined:
    Jan 8, 2017
    Posts:
    50
    I tested it and it works !!!
    Great, I solved my problem by myself !