Search Unity

  1. Looking for a job or to hire someone for a project? Check out the re-opened job forums.
    Dismiss Notice
  2. Unity 2020 LTS & Unity 2021.1 have been released.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Add animation to object through script

Discussion in 'Scripting' started by therobear, Mar 16, 2011.

  1. therobear

    therobear

    Joined:
    Sep 28, 2010
    Posts:
    22
    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!!
     
  2. JayShades

    JayShades

    Joined:
    Mar 13, 2011
    Posts:
    125
    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.
     
  3. therobear

    therobear

    Joined:
    Sep 28, 2010
    Posts:
    22
    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.
     
  4. JayShades

    JayShades

    Joined:
    Mar 13, 2011
    Posts:
    125
    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.
     
  5. PrimeDerektive

    PrimeDerektive

    Joined:
    Dec 13, 2009
    Posts:
    3,073
  6. therobear

    therobear

    Joined:
    Sep 28, 2010
    Posts:
    22
    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.
     
  7. rikin2344

    rikin2344

    Joined:
    Dec 19, 2012
    Posts:
    3
    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....
     
unityunity