Add animation to object through script

Hello,

Probably this question has been asked before, but I was wondering if there was a way to add an animation to an object through script. The project I am working on uses a lot of prefabs, and I don’t want to break the prefab by adding my own animation. We are using C# for scripting. I know that you can add scripts by using AddComponent, but this doesn’t work for animations. Thanks!!

This object you’re working with, is it rigged ? If it is, then adding animations are quite easy as you can use transform.Rotate or transform.position on any of the rigged parts to animate them.

No, the object isn’t rigged. I should of been a bit more clear. I have an animation clip that I would like to add to an object in a prefab through script so I won’t have to break the prefab. The object is like an access panel and the animation clip i created has the panel moving out of the way.

Ohhhhh that, well for that, as far as I know you cannot add an animation component to an object through code BUT you can run the animation for the object you want through another GameObject of which you’re willing to sacrifice the prefab connection using this

target = GameObject.Find(“accesspanel”);

target.animation.CrossFade(“moveOut”);

I donno if that will work but do give it a try if you’re willing to.

In the example there you would drag the clip file from your project to the “walkClip” variable, but you could also use Resources.Load() to populate it in Start() (but you would have to make sure you have the clip you are loading in a folder named Resources in your project).

Thanks for your help guys, I think I am just going to have to break the prefab. Trying these and different options lead me to the conclusion that I am going to have to break the prefab.

i wanted to know how do we go about animating a rigged model in unity using C#? Is there any code for it in C#? Thanks…