Hey, is there a way to change the “Motion” field in Animation State directly from code? My goal I want to achieve is set Motion as Serialaze Field parameter in Fighter.cs component. Then I want to set this motion to Attack Animation State in Start() function. This way I would have control over what animation is played on each character.
Yes there is, but it’s a little convoluted
var controller = myAnimator.runtimeAnimatorController as AnimatorController;
if (controller == null) return;
controller.SetStateEffectiveMotion(myAttackState, myAttackMotion);
See here
This, however, is not the way to do it. Take a look at AnimatorOverrideController
Hi, thanks for tips.
I’ve tried the more “convoluted” way so far. I asked chatGPT some questions and finally I could reach to AnimatorState that I wanted to change. Here is my code, but, to be honest, I don’t really understand that bit of code that ChatGPT has generated for me (it’s the 4th line).
animator = GetComponent<Animator>();
var controller = animator.runtimeAnimatorController as AnimatorController;
if (controller == null) return;
AnimatorState attackState = controller.layers[0].stateMachine.states.FirstOrDefault(x => x.state.name == "Attack").state;
controller.SetStateEffectiveMotion(attackState, attackMotion);
It works… kinda. Problem is that it changes the Animator that is shared throughout the project by all of my characters. So even if I have Motion SerializeField in prefab variants… all of character have the same animation regardless.
Now I will try the other way you proposed.
I don’t recommend this approach, it’s needlessly complex.
Ideally, you should be assigning a RuntimeAnimatorControllerOverride for each weapon or in the case of enemies, for that particular enemy if you have separate animations.
You can play an animation directly by the name of the state in the animation. This technique is used in our Third Person Combat and Traversal course. For this, you can change states (animations) with CrossFadeInFixedTime
animator.CrossFadeInFixedTime(AnimationName, TransitionDuration);
The AnimationName is the name of the STATE in the Animator, not necessarily the animation’s name. TransitionDuration indicates the amount of time to transition.
Yeah, the Animation Override Controler is the way for this. I took like two minutes to set up. Thank you again!
For those who are seeking quick answers:
- Create Animator Override Controler
- Setup Animator Override Controler
(I’ve changed only attack animation). - Don’t forget to change controller in your prefab variant
This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.