Hi! i know this question is asked every other week, but i searched the answers database and none of the answers i found were working for me and i didn’t want to comment on an old thread so I’ll just ask this again, how do i make this wait until the animation is finished?
function Play()
{
animation.Play("clip");
yield WaitForSeconds(animation["clip"].length * animation["clip"].speed);
//Do something when the animation is complete
}
To get an accurate accounting of the animation speed, you need to multiply it by 1/speed. In Unity a speed of 2.0 is twice as fast while a speed of 0.5 is half speed. Multiplying the length of an animation clip by speed won't produce the correct results. 1 second animation clip at speed of 2.0 should only be 0.5 seconds long. 1 * (1 / speed) Hope this helps clarify for people searching for this
I actually had to do this recently for my micro-script I put up on the Unity Asset Store: Animation Caller
However, what you can do for the script you have listed is to use the boolean function:
function Spawn()
{
animation.Play("DIE");
rigidbody.AddForce(Vector3.down * 200);
transform.position = spawn.position;
}
function Update()
{
if (!animation.IsPlaying("DIE"))
{
// The animation is finished
}
}
you can also replace the if statement inside of the update function with just:
function Spawn()
{
animation.Play("DIE");
rigidbody.AddForce(Vector3.down * 200);
transform.position = spawn.position;
}
function Update()
{
if (!animation.isPlaying)
{
// No animations are playing
}
}
but if i put the rest of the respawn code in that if statement, it will executed it whenever the animation is not playing and the player will be always respawning!
I’ve got a c# answer for this @captainvera It’s using the legacy animation system but this will work in Unity 5.6.
public string[] animClips = new string[2];
public float speed = 2.0f;
private Animation anim;
void Start()
{
anim = GetComponent<Animation>();
}
private void Update()
{
if (Input.GetKeyUp("a"))
{
StartCoroutine(Animate());
}
}
//use a coroutine so we can pause this function and wait for the animation to complete
public IEnumerator Animate()
{
anim[animClips[0]].speed = speed;
anim.Play(animClips[0]);
yield return WaitForAnim(anim[animClips[0]], speed);
}
IEnumerator WaitForAnim(AnimationState animclip, float spd)
{
tempTime = animclip.length * (1 / spd);
yield return new WaitForSeconds(tempTime);
}
void FunctionThatCallsYourAnimation()
{
Animator anim = YourGameObject.GetComponent<Animator>();
anim.Play("YourAnimationClip");
Invoke("ToDoAfterAnimationPlayed",lengthofanimation);
//float lengthofanimation = length of animation * speed of animation
}
void ToDoAfterAnimation()
{
// Code to be executed after Animation is played
}
try animation.IsPlaying("animation name") it return true/false. like: if(!animation.IsPlaying("Idel")) { //animation stop } else { //still playing }
– rodimus_strom