Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Playing new mecanim animations via old animation scripts

Discussion in 'Animation' started by Roachie, Sep 25, 2013.

  1. Roachie

    Roachie

    Joined:
    Aug 2, 2009
    Posts:
    67
    Hi everyone, i am not a modeller or animator however i recently was looking at purchasing some models off the store (which have mecanim animations).

    My old models relied on the old animation system , so i have a function such as where ani is a UnityEngine.Animation object

    private void PlayAnimation(string ani_name)
    {
    if (ani == null) return;
    ani.Stop();
    if (!ani[ani_name]) return;
    ani.Play(ani_name);
    }

    So my question is, how can i import these new models and update my script so i can easily just call the new models mecanim animation called "idle"

    throughout my scripts i have alot of

    PlayAnimation("idle");

    Thanks in advance
     
  2. TonyLi

    TonyLi

    Joined:
    Apr 10, 2012
    Posts:
    12,756
    You could stick with legacy if all of the Mecanim animations use the same skeleton as your models.

    But if you go with Mecanim, you've already made your life a lot easier by wrapping calls to the Animation component inside that PlayAnimation() method. You just need to change what PlayAnimation() does internally.

    It seems to me that the simplest solution would be to create Boolean animator parameters with the same name as the animation clips ("idle", etc.). Then create transitions from Any State to the appropriate clip, one for each parameter.

    Then your PlayAnimation() can be as simple as:

    Code (csharp):
    1.  
    2. private void PlayAnimation(string parameter) {
    3.     animator.SetBool(parameter, true);
    4. }
    5.  
    (For clarity, I omitted error checking in the code above.)

    The only catch is that you need to set the parameter to false after transitioning. Otherwise it will keep transitioning repeatedly from Any State to the animation clip, resulting in a weird stuttering behavior.

    A couple options come to mind:

    1. Use the Event System for Mecanim (available for purchase in asset store).

    2. Record the parameter name in PlayAnimation(). In Update(), if the transition is active, set that parameter to false.

    3. Instead of using Any State, create transitions between the actual animation states. You'll avoid the stutter, but it may require a lot more transitions.

    From there you could modify your state machine to be more sophisticated and take better advantage of the power of Mecanim's transitions. But this would get you up and running quickly.
     
    Last edited: Sep 25, 2013