- Home /
How to create and run an animation at runtime?
I'm making a game currently and want to create and run an animation at runtime. The Array sprites contains the different images for the animation. This is what I got so far:
void Start()
{
Sprite[] sprites = upgrades.GetComponent<uprgades>().sprites;
AnimationClip animClip = new AnimationClip();
animClip.frameRate = 60;
EditorCurveBinding spriteBinding = new EditorCurveBinding();
spriteBinding.type = typeof(SpriteRenderer);
spriteBinding.path = "";
spriteBinding.propertyName = "m_Sprite";
ObjectReferenceKeyframe[] spriteKeyFrames = new ObjectReferenceKeyframe[sprites.Length];
for(int j = 0; j < (sprites.Length); j++)
{
spriteKeyFrames[j] = new ObjectReferenceKeyframe();
spriteKeyFrames[j].time = j;
spriteKeyFrames[j].value = sprites[j];
}
AnimationUtility.SetObjectReferenceCurve(animClip, spriteBinding, spriteKeyFrames);
AnimationClipSettings animClipSett = new AnimationClipSettings();
animClipSett.loopTime = true;
animClip.legacy = true;
AnimationUtility.SetAnimationClipSettings(animClip, animClipSett);
I don't understand everything completely cause I found this in the internet. But now I need to start the animation right ? So I did this:
Animation anim = someGameObject.GetComponent<Animation>();
anim.clip = animClip;
anim.Play();
}
But this doesnt work. I think it has something to do that I don't have any Animator / or Controller but I don't know if I have to add them how and where I should do this
Comment