Triggering an animation once in mecanim

Hi there,

Within one of my animators I am tracking whether or not to transition into another state using a bool and the SetBool() function.

However I seem to have the problem of if I turn the bool back to being false mid animation, the transition goes back to my idle too quickly and doesn’t play the animation all the way through, even if the conditions-to-transition-back-to-idle are set to ExitTime&bool=false.

Can anyone tell me what I need to do to set the bool back to being false at the right time / how I can get mecanim to play an animation once?


If possible as well I’d also like to have the ability to interrupt the animation and get it to transition to its beginning (in my case ‘shoot a gun animation with a little recoil afterwards getting interrupted by firing the gun again’).

The easiest way is to use the “Trigger” parameter type for the transition in the Animator state editor. It’s a bool that sets itself to false immediately after the transition.

I was using animation events and scripted the bool reset before I came across this.

The example scripts provided by Unity use GetCurrentAnimatorStateInfo(). In Update(), it checks if you’re in the “shoot gun” state. If so, it clears the bool. Check the bazooka script in the IK scene (Mecanim Example Scenes | Tutorial Projects | Unity Asset Store).

It sounds like you’ve maybe marked the shoot–>idle transition as non-Atomic. Try ticking the Atomic checkbox. Also, is the exit time correct?

Otherwise, I’d guess it’s in the logic of how/when you’re setting the bool. You should be able to clear the bool as soon as you’re in the shoot state (actually, as soon as the transition to shoot has started).

If you clear it at this point, then you have two choices for interrupting the animation and starting it over right away:

  1. Create a transition from Any State–>shoot, or
  2. Create a null state. Create a transition from shoot–>null (if bool is true) and then null–> shoot (again if bool is true).

A bit from here a bit from there I get it solved, here is the how to:

  • Create an animation by dragging X
    sprites onto the scene
  • Open the animation controller
    that is created (you can find it on
    the sprite asset folder)
  • Create a trigger shouldAnimate
    (on top left you find parameters,
    click on +)
  • Create an empty state
  • Set the default transition to the
    empty state
  • From the new state add a
    transition to the animation state
  • Under the transition condition
    add the shouldAnimate trigger
  • Create an empty transition from
    the animation to the new state
  • From code call
    myAnimator.setTrigger(“shouldAnimate”)
  • ENJOY :smiley:

Cheers

Click on your transition and set it to “Solo”. That should force the animation to play fully before it goes back (even if you set the bool to false before the full playthrough).