0
\$\begingroup\$

I'm working on functionality in Unity where if a game object's health is zero, it does and the object is destroyed. This works fine as is, I reduce the health to zero, the die animation plays and the game object is destroyed. I want to have the script wait a certain amount of time and then run the destroy method. I thought using WaitForSeconds() would do the trick, and technically, it does, but the death animation continues to play until the object is destroyed. My question is, how do I get the animation to stop playing as the script waits to destroy the object?

C#

void Die(){
    GetComponent<Animation>().CrossFade(die.name);
    //If the current animation time is greater than 90% of the entire animation length, destroy the object.
    if(GetComponent<Animation>()[die.name].time > GetComponent<Animation>()[die.name].length * 0.9){
        StartCoroutine(RemoveBody());
    }
}

IEnumerator RemoveBody(){
    yield return new WaitForSeconds(5);
    Destroy(gameObject);
}
\$\endgroup\$
1
\$\begingroup\$
using UnityEngine;
using System.Collections;

public class Die : MonoBehaviour {
    public Animator anim;// Animator component
    public bool check;// Check animation is done
    public float DonePercent = 1;// 100% of the entire animation length.you can change it by 0.5f then %50 of the entire animation length.
    void Start() {
        anim = GetComponent<Animator>(); // access to animator component
        StartCoroutine (CheckIsDoneAnimation ()); // start coroutine
    }
    void Update(){
        check = anim.GetCurrentAnimatorStateInfo (0).normalizedTime > DonePercent && !anim.IsInTransition (0); // if animation is done by DonePercent
    }
    IEnumerator CheckIsDoneAnimation(){
            yield return new WaitUntil (() => check == true);
            print ("Works!");
        Destroy (gameObject);
    }
}

it didn't need coroutine I just show you how you can wait until work finish in coroutine.so you can check when animation finished then destroy object.

using UnityEngine;
using System.Collections;

public class Die : MonoBehaviour {
    public Animator anim;
    public float DonePercent = 1;
    void Start() {
        anim = GetComponent<Animator>();
    }
    void Update(){
        if(anim.GetCurrentAnimatorStateInfo (0).normalizedTime > DonePercent && !anim.IsInTransition (0)){
            print("works! without coroutine");
            Destroy (gameObject);
        }
    }
}

perhaps you ask me what is usage this "()=>" you can know it on this link.

this is helpful about waituntil-waitwhile-in-unity

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .