Unity Destruir después de hacer animación

Supongamos que queremos crear un animación en un GameObject que tras ejecutarse se destruya asimismo, tendriamos varias opciones la mas sencilla es contar el tiempo en segundos y simplemente usar la funcion Destroy(gameObject,segundos_animacion); si embargo este codigo requiere ajustes y no es universal.
El codigo para que un GameObject se destruya tras ejecutar una animación seria:
public class Destruye : MonoBehaviour {

Animator animator;
float tiempo;
void Awake(){
animator = GetComponent ();
}

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
//Que la animación coincida con el tiempo
if (animator.GetCurrentAnimatorClipInfo(0).Length != 0)
{
AnimatorClipInfo[] AuxClipInfo = animator.GetCurrentAnimatorClipInfo(0);
tiempo = animator.GetCurrentAnimatorStateInfo(0).normalizedTime * AuxClipInfo[0].clip.length;

if (tiempo > AuxClipInfo[0].clip.length)
{
print (tiempo + " " + AuxClipInfo [0].clip.length);
Destroy (gameObject);
}
}

}
}

Tendremos que asignarlo al GameObject que tenga el Animator y ademas quitar el loop de la animación, este código es universal, ya que recoje el tiempo que dura el clip y lo compara con ese tiempo multiplicado por el tiempo normalizado es decir, en base 1, funcionando como un porcentaje .
Cuando tiempo sea mayor que la duración del clip, es un poco mayor por la multiplicación y el numero de decimales, destruye el gameObject que lleva este script asociado.
Respecto al 0 de animator.GetCurrentAnimatorClipInfo(0); se trata del LayerAnimation que si no hemos creado ninguno mas sera la Base Layer y por tanto valdrá 0.

Ad debug output

The ad is displayed on the page

current post: Unity Destruir después de hacer animación, ID: 2419

Ad: Anuncio2 (2573)
Placement: After Content 2 (after-content_2)

Display Conditions
general conditions
Adwp_the_query
term_id0
taxonomy0
is_main_query11
page01
numpages01
is_archive1
is_search1
is_home1
is_4041
is_attachment1
is_singular11
is_front_page1
is_feed1




Find solutions in the manual

Leave a Reply

Your email address will not be published. Required fields are marked *