Sign in to follow this  
lougv22

Unity How to add and delete Transitions (in Unity's Mecanim system) in script?

Recommended Posts

lougv22    392

So I have the following situation that cannot be easily handled with a Mecanim State Transition chart: I have a high number of animations for the same character in my game, let's say about 50. Let's call them Attack 1Attack 2, ....Attack 50, just for illustration purposes. So far I am able to easily add them as States to an Animation Controller and add Transitions for them from my Idle state. So far so good, I can perform each animation individually and that works just fine.

Here comes the problem though. Next, I want to be able to perform multiple animations one after another, as soon as the previous one ends, with just one button click. For example, when the player hits the A button, I want the character, who is already in Idle state, to do Attack 1 --> Attack 2 --> Attack 3 --> Idle. I figured out I could do that by creating a Transition from Idle to Attack 1 with a Boolean parameter that is set to True when the player hits a certain button, then another Exit Time Transition from from Attack 1 to Attack 2, then the same (Exit Time) from Attack 2 to Attack 3, and finally from Attack 3 to Idle. Basically I created a Transition loop (in the image below Attack 1 is "punching_2", Attack 2 is "roundhouse_kick_2 0", and Attack 3 is "leg_sweep_2 0", and the Transitions in the loop are highlighted in Blue):

 

Mecanim_State_Transitions_Chart_zps1ab10

 

While that works fine, it's a problem when you have a lot of animations and need to be able to perform pretty much every permutation of length 4 or less. For example, what if I need to perform the following animation combinations?


  • Attack 1 --> Attack 2
  • Attack 2 --> Attack 1
  • Attack 1 --> Attack 2 --> Attack 3
  • Attack 1 --> Attack 3 --> Attack 2
  • Attack 2 --> Attack 1 --> Attack 3
  • Attack 2 --> Attack 3 --> Attack 1
  • Attack 3 --> Attack 1 --> Attack 2
  • Attack 3 --> Attack 2 --> Attack 1
  • Attack 1 --> Attack 2 --> Attack 3 --> Attack 4
  • etc. etc. etc.

I think you see where I am going with this. If I were to attempt to create a State Transition loop like the one in the image above for every single combination in the Animator Controller editor, things would get out of hand, and flat out impossible to keep track of, very fast.

So here comes my question: is there a way to add and delete Transitions programmatically so I can create loops like the one above for the particular animation combination I need on the fly? Let's say I want to perform the combination Idle --> Attack 20 --> Attack 34 --> Attack 9 --> Attack 11 --> Idle. I would then create the necessary Transition between the desired States in script and run them upon a button hit. After that I would delete the Transitions.

If that is not possible, how else can I handle the situation I described above?

Edited by lougv22

Share this post


Link to post
Share on other sites
DiegoSLTS    2113

I don't have a lot of experience with animations, but I read that you can't edit animations on runtime inside a script.

 

Anyway, if you'll setup all the transitions just to play it once and then rollback it sounds like you're doing a lot of unnecesary work. I'm pretty sure you can just play the animations in the order you want, use the Animation's "Play" method to start a new animation when the current one has finished or go back to idle if it's the last one. Check in the Update method if the animation finished, here someone asked how to do it and it looks really simple: http://answers.unity3d.com/questions/362629/how-can-i-check-if-an-animation-is-being-played-or.html

Edited by DiegoSLTS

Share this post


Link to post
Share on other sites
lougv22    392

I don't have a lot of experience with animations, but I read that you can't edit animations on runtime inside a script.

 

Anyway, if you'll setup all the transitions just to play it once and then rollback it sounds like you're doing a lot of unnecesary work. I'm pretty sure you can just play the animations in the order you want, use the Animation's "Play" method to start a new animation when the current one has finished or go back to idle if it's the last one. Check in the Update method if the animation finished, here someone asked how to do it and it looks really simple: http://answers.unity3d.com/questions/362629/how-can-i-check-if-an-animation-is-being-played-or.html

 

Thanks for your reply. I ended up with a slightly different approach. It is definitely not ideal, but it works. It's not ideal for two reasons: first, it uses co-routines. I know some people scoff at them in disdain, but this was the best way I could find to reliably wait until an animation has finished before playing the next one. The problem was that the sequence of animations is triggered upon a button click in my Update method (which executes every frame) and you have to use a combination of Boolean flags and animation state checks to see if an animation has ended or not, which I actually tried, but for whatever reason the state was always the previous one (Idle) and not the one corresponding to the animation being played.

 

The second reason why it's not ideal is because I ended up hard-coding the length of each animation. I know that's a hack, but again, I could not find a good way to obtain the length of an animation. I tried the code below, but it didn't work. Just like above, the problem was that when checking which animation state the character was in, it always came back as the previous one. Maybe in Unity 5.0 there'll be a better way to do this:

public float GetAnimationLength (int animationNameHash)
{
    // The length of the animation state.
    float animationLength = 0.0f;

    // Now obtain the animator component of the player.
    Animator animator = player.GetComponent<Animator> ();
    if (animator != null)
    {
        // Get the current animation state.
        AnimatorStateInfo animationState = animator.GetCurrentAnimatorStateInfo (0);

        if (animationState.nameHash != animationNameHash)
        {
            animationLength = -1;
        }

        // Now get the the clips in the current animation state. The first
        // clip in the array is the one corresponding to the desired
        // animation state.
        AnimationInfo[] animationInfo = animator.GetCurrentAnimationClipState (0);
        if (animationInfo.Length == 0)
        {
            throw new UnityException ("There are no clips associated with animation " + animationNameHash);
        }

        AnimationClip animationClip = animationInfo [0].clip;

        // Finally, get the length of the desired animation state.
        //animationLength = animationClip.length * animationState.normalizedTime;
        animationLength = animationClip.length;
    }
    catch (UnityException unityEx)
    {
        throw new UnityException ("Could not get length for animation " + animationNameHash + ". Error is: " + unityEx.ToString ());
    }

    return animationLength;
}

So here is the solution I came up with, in case someone is interested. If somebody can tell me a reliable way to find an animation's length, that would be awesome:
 

  1. In my Mecanim State Transition diagram, I added transitions to all the animations from Any State, with a parameter of type Trigger.
  2. I added the method below for playing the animations, stored in a List, in a sequence:
public IEnumerator PlayAll ()
{
    // Now obtain the animator component of the player.
    Animator animator = player.GetComponent<Animator> ();
    if (animator != null)
    {
        float animationLength = 0.0f;
        foreach (String animParameter in AnimParameters)
        {
            animator.SetTrigger (animationParameter);
            // Get the length of the current animation.
            // GetAnimationLength just has the hard-coded lengths
            // of all animations.
            animationLength = GetAnimationLength (animParameter);
            yield return new WaitForSeconds (animationLength);
        }

        animator.Play ("bouncing_fight_idle_1", 0, float.NegativeInfinity);
    }
}

   

    3. And this is how I call the method above:

       

void Update ()
{
    if (Input.GetKeyDown ([some button code here]))
    {
        StartCoroutine(PlayAll);
    }
}

Any comments and constructive criticism are welcome.

Edited by lougv22

Share this post


Link to post
Share on other sites
frob    44973

I suppose another quick blurb on this...

 

The invisible no-animation mini hubs can also work well for organization.  A quick hand-drawn sketch rather than building the graph with all the transitions, it looks something like this:

 

[attachment=25917:bigger_sub-hub.png]

 

So they enter through an invisible starting node, transition to a big central zero-time invisible hub, transition out to an invisible cluster for whatever makes sense (for example, this is what quite a few Sims3 animation graphs looked like, including the dance floor mentioned above), then they can bounce around in as many (blue) invisible nodes as they want. The key is those yellow nodes where the animation takes place. Do transition animations as you enter, not as you exit. And when they're done, they exit potentially playing a final transition animation on the way out..

Share this post


Link to post
Share on other sites
lougv22    392

Hi frob

 

Thanks for your detailed answer. There are a couple of things I don't understand though. First, isn't the mid_attack_hub node in your example the same as Any State? If not, what are the differences? In your example State Transition chart, you can go to any of the Attack animations from it, which is very similar to what I do now. Here is the relevant portion of my new State Transition chart:

 

State_Transition_Chart_Any_State_zps6fcd

 

The second thing I don't understand is the following:

 


With the invisible hub your code has a landing pad to chain together as many actions as you want in any order you want. Call the two animation states in quick succession, attack2 then mid_attack_hub; attack1 then mid_attack_hub; attackX then mid_attack_hub. When the chain is over transition back into your regular idle.

 

How do you call your animations in quick succession and how do you make sure an animation is completed before starting the next one? Can you go into more detail on this, preferably with a code sample?

 

Thanks!

Share this post


Link to post
Share on other sites
frob    44973
Those are all related.

If you allow transitions from any state, you are right that calling .Play() can interrupt like that. Allowing an Any State transition means you can be interrupted by yourself and other problems. Only use transitions from "Any State" if you really mean you can enter from anywhere, including entering from your own current state and entering from somewhere completely unrelated.

Instead of "Any State", if you require it to follow through the machine you can specify in each transition how far along the clip must before the animation controller will advance. Make sure it is marked as atomic and the slider is far enough over that the entire critical portion of the animation will play. Then you can set your transition conditions or triggers or other values. With that done, you can either tell the state machine to move from state to state manually or allow the Animator object to do all that for you.

As for code, there are really so many options that it depends on how you chose to go.

If you are calling the animator's Play function (not the animation's Play function) it will queue up the transition through the next state. From there you can rely on animation events, or rely on checking that the current state is not transitioning, or use GetCurrentAnimationStateInfo to ensure you are in the correct state, or many other things besides.

OR instead of calling the animations directly you can use triggers and conditions to jump from state to state by you setting states, then use animation events to trigger the different animations. From there you can again use animation events or testing the current state. In that case the only code required is setting an appropriate flag in the animator with SetBool() or SetInteger() or SetTrigger() whatever you need to cause the values you set to happen. Then when the current animation is ready to advance it will test the values and transition based on the condition values and triggers you provided.

OR you could go back to the legacy system and call each animation directly rather than letting the Animator (the script object, not the human) do the work, queuing up the transitions yourself.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this