- Home /
Access Animation States in Mecanim at runtime
I need to change different properties of states in Mecanim at runtime(Mainly animation-speed and animation-clips). I found a way to make it work:
UnityEditorInternal.AnimatorController ac = animator.runtimeAnimatorController as UnityEditorInternal.AnimatorController;
UnityEditorInternal.StateMachine sm = ac.GetLayer(0).stateMachine;
//set the animationclip to the one that is set for the current attack
sm.GetState(1).SetAnimationClip(animationClipToolStart);
sm.GetState(2).SetAnimationClip(animationClipToolEnd);
//set the speed of the animation so that it ends when startupTime is over
sm.GetState(1).speed =(float)(animationClipToolStart.length/startupTime);
sm.GetState(2).speed =(float)(animationClipToolEnd.length/cooldownTime);
It works fine inside the Editor. However, when I try to Build it, I get the error that the UnityEditorInternal Namespace was not found(which makes sense, because Unity probably doesn't export the Editor features for the final game). Therefore, I wanted to ask if there is a way around this error-message, or if someone has an idea for a good alternative.
I would like to know the answer to this question also.
$$anonymous$$y current workaround is that I am using .ForceStateNormalizedTime() on the animator when it has found a clip that I have marked as needing a new speed. It then manually sets the progress of the animation.
I now just used the old Animator Component. And wrote the state changing manually per script. In the old Animator Component you can change the speeds.
Answer by vanmani · Mar 30, 2015 at 04:07 AM
You will be able to solve this problem in 5.1. You cannot currently solve this problem in a good way.
This problem has been experienced by hundreds of users, and relates to the design of Mecanim. The problem seems to be that the state machine is not instanced at runtime - so any changes you make to it at runtime would be permanent. As such, they don't expose any of it at runtime.
They're fixing it by allowing you to drive the speed of an animation state via parameter in 5.1. A bit of a hacky solution if you ask me, but a solution nonetheless.
Wrote all about it on my blog if you want to know more.