Gun Animations Aren't Playing Right Away?

Basically I have a script that plays its animation according to the buttons being pressed. For example,

Doing nothing = Idle Animation
Walking = Walking Animation
Walking + Sprint = Sprint Animation

The script works perfectly, The only Problem is that whenever i go from walking or sprinting to Idle, The walking or sprint animation continues to play for a brief sec or so and THEN changes to the idle Animation. This only happens when i go to the Idle animation. I want it to changes instantly, like it does from walking to sprinting or vice versa.

Heres my script :

var PlayerState : float;
var PlayerAnimSec : GameObject;
var PlayerMotor : CharacterMotor;
var WalkingSpeed : float = 6;
var SprintSpeed : float = 9;

function Update (){

PlayerStateController();
PlayerAnims();
}



function PlayerStateController(){

	if((Input.GetAxis("Vertical") !=0 || Input.GetAxis("Horizontal") !=0)){
	
	if(Input.GetButton("Sprint")){
	
		PlayerState = 2;
	
	}else{ PlayerState = 1;}

}else{ PlayerState = 0;}}


function PlayerAnims(){

if (PlayerState == 0){

	PlayerAnimSec.animation.CrossFade("IdleAnimation", 0.4);

}

if (PlayerState == 1){

	PlayerAnimSec.animation.CrossFade("WalkingAnimation", 0.4);
	
	PlayerMotor.movement.maxForwardSpeed = WalkingSpeed;
	PlayerMotor.movement.maxBackwardsSpeed = WalkingSpeed;
	PlayerMotor.movement.maxSidewaysSpeed = WalkingSpeed;
	
	

} if (PlayerState == 2){

	PlayerAnimSec.animation.CrossFade("SprintAnimation", 0.4);
	
	PlayerMotor.movement.maxForwardSpeed = SprintSpeed;
	PlayerMotor.movement.maxBackwardsSpeed = SprintSpeed - 2;
	PlayerMotor.movement.maxSidewaysSpeed = SprintSpeed;
	
}
}

Thanks for the help!

I’m not sure how to solve it, but here is my guess.
What I think that could be happening is that you are playing the animations over and over again, as it’s been called on Update(). A simple way to solve it would be to check is the animation isn’t already playing before telling it to start playing. Like:

if (PlayerState == 0){
    if(!PlayerAnimSec.animation.IsPlaying("IdleAnimation"){
        PlayerAnimSec.animation.CrossFade("IdleAnimation", 0.4);
     }
}

Just make sure I got the right sintax…
Hope that helps, it’s just a guess.

The second parameter of CrossFade is a fade length. There’s a pretty big chance that if you set this to 0.0F ( means 0sec ), it will fade instantly