Hey, I wanted to let an animation play once from the start and the loop the last 20% a few times. I use the following line. animator.Play("myAnimation", 0, 0.80f); This is causing issues because the States OnStateEnter() function gets called each time it loops. I try get around this by doing the at the top of OnStateEnter() if (currAnimLoop != 0) return;//skip OnStateEnter while you are looping. However this just seems very hacky. Is there a better way to do this? Thanks!
I'd recommend not using state machine behaviours' OnStateEnter/OnStateExit, because them getting called has very little to do with if the state's getting entered and exited, as you've discovered.
I think you're better off solving this in the Animator/State Machine itself, rather than trying to hack it through code. Create a state that is just the last 20% of the animation and one that is the first 80%. Transition straight from the 80% to the 20% in normal case, but have that 20% state loop under whatever circumstances you deem fit.
Agree with Praetor, but let me add this: on import you can import the animation as two separate clips, one from 0 to 80%, the other from 80% to 100%... make 2 mecanim states, one for the first part, one for the last part and loop the last part, and put no transition time or overlap between them. If there's a hiccup, play with the import boundaries until it works smoothly.
I just refamiliarized myself with this because I am planning to use it in the very near future... it works flawlessly, but it can be touchy to set up. I set it up with a Blender3D object so I included that example below. You'd need to install Blender3D if you wanna import it. Here's the Blender3D timeline view of the animation span, and it loops at frame 50: Here's the Unity3D model importer view, which is zero-based instead of 1-based like Blender: And the project is attached as a .unitypackage and scene and controller and all the animation setup. Again, you will NEED Blender3D if you want to see this, otherwise nothing will import. Video: