My character, if he gets hit during the middle of an attack animation, transitions to the “hurt” animation as he should – however, the attack collider that was on during mid-swing remains on while he’s recoiling from the enemy’s blow. Manually turning it off in the script when the enemy attacks doesn’t seem to work (though my breakpoint shows it happens), possibly due to some kind of race condition. Not using the hurt animation does fix the problem, but of course, I want that animation.
This would work, but the collider would then have to be keyframed into every animation that the attack animation can transition to, which felt like an unwieldy solution to me.
Well, the way I set it up was by recording the attack animation and turning the colliders on for the entire set of frames that the sword was in action, then off when the sword was retracted. Seems that when the animation is interrupted mid-swing, the collider doesn’t know to turn off until after the interrupting animation (getting hit) completes. Hmm.
If the value is false when you start playing back the animation, it should be false during all of the animations that doesn’t have a keyframe for that value, if those animation states have “write defaults” checked.
All of that is complicated enough that my suggestion is to not have the value based on being recorded. My suggestion is this:
Use an animation event to turn on the hitbox.
Use a coroutine to turn off the hitbox.
When you trigger the hurt animation (or other animations that can cancel the animation event), also turn off the hitbox.
The reason to use a coroutine over an event to deactivate it is because it acts as a failsafe - if you add an animation cancel, but forget to add the “deactivate hitbox” code there, you won’t end up in a state where the hitbox is permanently active.
You could alternatively just use a coroutine to both activate and deactivate the hitbox. That makes it slightly harder to time the start properly, but it’s a lot less complex to deal with code-wise.
Oh jeez if you’re doing 2D don’t use mechanim at all.
The Animation component is still supported, and is both easier to use and much more performant (by ~2x in my tests) than the Animator. Alternatively, do what we’re doing and just write a component that swaps sprites.
The whole point of the Animator/AnimatorController (“mechanim”) is to blend between animations. You don’t blend when doing sprite sheet animations, so all the slowness and complexity has zero usefulness to you.