- Home /
Destroy Object After Animation is Completed
Hey guys,
Ive managed to get a small prototype working where when the player enters a trigger then a animation is played. The issue im having is that once the animation has played the object should be destroyed but it doesnt seem to do that.
the code i have is:
private GameObject activationPortal;
Animator portalActivator;
// Use this for initialization
void Start () {
activationPortal = GameObject.Find("PortalActivate");
activationPortal.gameObject.SetActive(false);
portalActivator = activationPortal.GetComponent<Animator>();
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Destroy(gameObject);
activationPortal.gameObject.SetActive(true);
portalActivator.Play("PortalActivation");
StartCoroutine(PortalAnim(portalActivator.GetCurrentAnimatorStateInfo(0).length));
}
}
public IEnumerator PortalAnim(float waitTime)
{
yield return new WaitForSeconds(waitTime);
Destroy(activationPortal);
}
For some reason the Destroy(activationPortal);
is never reached. Unless ive done something wrong.
Any help will be appreciated.
Thanks!
Answer by Zetya96 · Dec 07, 2017 at 06:04 PM
Your approach is wrong You destroy the gameobject on line 15. If you destroy the gameobject that the script is attached to, the script will be destroyed too, so the next line will never execute.
ah of course! I knew it was going to be a simple mistake! silly mistake on my part. thank you.
Interesting, I just made a dummy, and the line after destroy IS being called.
However the coroutine will not be invoked, cause its already destroyed.
Destroy happens on the end of the frame, not when called, so the rest of the code will executed normly. Also the coroutine will get executed till it reaches the first yield statement (in this case it is first), but it will stop there as it returns control to the caller and eventually the object is destroyed and with it stops the coroutine too as they are closely linked. Check this
Answer by tormentoarmagedoom · Dec 07, 2017 at 04:55 PM
debug and check if the line is beeing executed, and post the result
whats the best way to go about debugging it? breakpoints?
Debug.Log(string). then, if it appears in the console, youre golden. :)
Your answer
Follow this Question
Related Questions
activate an inactive GameObject with yield return new WaitForSeconds doesnt work 1 Answer
Show animation after destroy object 0 Answers
Unity destroy animated value ? 0 Answers
Game object delete itself from hierarchy when I play animation 1 Answer
Can the animation editor create local rotational data? 3 Answers