- Home /
How to play an animation at least once before changing
Hello guys! I've got an enemy with attack and running animations, and will only do these at a certain range. Problem is that when I go between two given ranges too fast, the animations immediately change, making it unrealistic. I've tried using animation.CrossFade but it doesn't work much, so any ideas on how to fix this? Oh, and here's my script:
var Player : Transform;
var MoveSpeed = 1;
var MinDist = 2;
var MinDist2 = 4;
var Unseen = 15;
function Update ()
{
transform.LookAt(Player);
if(Vector3.Distance(transform.position, Player.position) <= MinDist)
{
Debug.Log("Attacking");
if(!animation.IsPlaying("Attack"))
animation.CrossFade("Attack");
}
if(Vector3.Distance(transform.position, Player.position) <= MinDist2)
{
if(Vector3.Distance(transform.position, Player.position) >= MinDist)
{
Debug.Log("Attacking2");
if(!animation.IsPlaying("Attack2"))
animation.CrossFade("Attack2");
}
}
if(Vector3.Distance(transform.position, Player.position) >= MinDist2)
{
if(Vector3.Distance(transform.position, Player.position) <= Unseen)
{
Debug.Log("Not in attack range");
transform.position += transform.forward * MoveSpeed * Time.deltaTime;
if(!animation.IsPlaying("Running"))
animation.CrossFade("Running");
}
}
if(Vector3.Distance(transform.position, Player.position) >= Unseen)
{
Debug.Log("Not within sight");
if(!animation.IsPlaying("Idle"))
animation.CrossFade("Idle");
}
}
That's it. If possible, I want to be able to play the "Attack" animation at least once before switching animations. Thank you very much in advance, and have a good day!
Answer by deltamish · Apr 15, 2014 at 04:18 PM
Hi you set a higher CorssFade Time
// I have edited your code a bit
if(Vector3.Distance(transform.position, Player.position) <= MinDist2)
{
Debug.Log("Attacking2");
if(!animation.IsPlaying("Attack2"))
animation.CrossFade("Attack2",0.7f);
}else if(Vector3.Distance(transform.position, Player.position) <= MinDist) // used else if to check if its greater than "MinDist2" value and less than "MinDist"
{
Debug.Log("Attacking");
if(!animation.IsPlaying("Attack"))
animation.CrossFade("Attack",0.6f); // U could also try using CrossFadeQued
}
Tested and is working properly with a few adjustments. Thanks!
Answer by JCX · Apr 15, 2014 at 08:45 AM
use Animator, there you can visually set this up, Animation is deprecated anyway
Any other ways? Oh, and thanks for the quick reply!
Your answer
![](https://koobas.hobune.stream/wayback/20220613142741im_/https://answers.unity.com/themes/thub/images/avi.jpg)