Hey guys have a project due friday and the last thing im trying to figure out is how to play an animation before destroying a game object . its basically a key pick up .Ive tried to use invoke etc but with no luck if anyone can help I would be very great full
Invoke should work. You can then use AnimationClip-length and/or AudioSource-clip before destroying your object.
Instead of directly calling Destroy(gameObject)
you can invoke your IEnumerator function in which you can wait until the animation clip/ audiosource clip length has expired after which the Destroy(gameObject) can get called.
Since i prefer Coroutine i am calling the IEnumerator with StartCoroutine and passing the waiting time as a parameter. Alternatively you can use Invoke and get the desired waittime in the ienumerator.
Untested but should work something like that.
using System.Collections;
public class KeyPickUp : MonoBehaviour
{
//[...]
IEnumerator PlayAnimationAndDie(float waitTime)
{
animation.Play("animationNameYouHaveUsed");
AudioSource.PlayClipAtPoint(KeyGrab, transform.position);
yield return new WaitForSeconds(waitTime);
Destroy(GameObject)
}
void OnTriggerEnter (Collider other)
{
if(other.gameObject == player this.gameObject.tag == ("KeyCardA"))
{
playerInventory.hasKeyA = true;
StartCoroutine("PlayAnimationAndDie", animation.clip["animationNameYouHaveUsed"].length);
////Invoke("PlayAnimationAndDie",0); then you would have to get the length value in the IEnumerator
}
}
//[...]
}
Thanks guys that worked great , used the bool version and works perfectly , i do however have to get my head around coroutenes really thanks , here`s the working script is anyone wants an answer
Worth noting is that you can actually pass a delay to Object.Destroy. So you could do Destroy(gameObject, animation["animationName"].length); to destroy the object after the length of animation “animationName”.