Load, modify and save animation with code

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

AnimationEvent[] aEvents = null;
// Load the multitexture 
UnityEngine.Object[] textures  = Resources.LoadAll("my_spritesheet");
int FrameNb = textures.Length - 1;

// Load the animation asset
string asset_path = "Assets/Animations/my_anim.anim";
AnimationClip animClip = (AnimationClip)AssetDatabase.LoadAssetAtPath(asset_path, typeof(AnimationClip));

animClip.name = "my_anim";
animClip.frameRate = FrameNb;
float time = 1f / FrameNb;

// create Editor Curve Binding
EditorCurveBinding curveBinding = new EditorCurveBinding();

// put the typeof(SpriteRenderer) as the binding type.
curveBinding.type = typeof(SpriteRenderer);
// Regular path to the gameobject: empty string means root
curveBinding.path = "";
// property name to change the sprite of a sprite renderer
curveBinding.propertyName = "m_Sprite";

// An array to hold the object keyframes
ObjectReferenceKeyframe[] keyFrames = new ObjectReferenceKeyframe[FrameNb];

for (int i = 0; i < FrameNb; i++)
{
    keyFrames[i] = new ObjectReferenceKeyframe();
    // set the time
    keyFrames[i].time = i * time;
    // set reference for the sprite you want
    keyFrames[i].value = textures[i + 1];

}

// Create animation event
aEvents = new AnimationEvent[1];
aEvents[0] = new AnimationEvent();
aEvents[0].functionName = "AttackEnd";
aEvents[0].time = (FrameNb - 1) * time;
animClip.events = aEvents;

AnimationUtility.SetObjectReferenceCurve(animClip, curveBinding, keyFrames);

animClip.EnsureQuaternionContinuity();
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 !

2 Likes

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?

1 Like

I tested it and it works !!!
Great, I solved my problem by myself !

3 Likes