I have an enemy with a collider trigger. When the enemy gets hit by a bullet, it reduces his hitpoints, pretty basic.
The issue I’ve run into is that when the Enemy’s HPs are less than or equal to 0, I want to move the gameobject off the screen and disable it. All of this works great. I just created a “dead” animation when the enemy is killed, so he falls to the ground. The problem I have is that the animation plays after the object is moved and disabled, instead of before. I’ve tried different methods to fix this, but haven’t been successful. I tried using coroutines(not sure how these work exactly), but couldn’t get it working that way either. Here is the basic script I am working with:
I also tried moving the code from the if statement “Enemy < 0” to the update function. I am probably way off track here, since I’m still learning how to code this type of stuff, but any help on how to get the animation to finish before the object gets disabled and moved would be greatly appreciated.
there are two ways to do that.
the first way is to create an animation using unity’s animation window located in window/animation. in this way you can attach a script to your animatino and execute it when you want (at the end). to read more on animation window click here. also you can add events to animations using code.
the second way is to run an animatino in a coroutine and wait until it’s time and then execute your other code.
function Die ()
{
animation.Play("die");
yield WaitForSeconds (animation["die"].length);
Destroy(this.gameObject); //destroys the object after animation ended
}
this code assumed the name of animation to be dead. you simply can define a variable as var clip : AnimationClip and use it to drag the animation to your gameObject. also you can add 0.5 to the animation.length property to destroy the gameObject a litle after completing the animation. to add events by hand to specific times to animations also you need to use the AnimationClip class.
You use coroutines. I don’t use javascript so I can’t give you the exact code you can copy/paste, but here’s the C# version of what you’re trying to do (in a nutshell):
void Update()
{
if(animationTime)
StartCoroutine(DoAnimation());
}
IEnumerator DoAnimation()
{
animation.CrossFade("MyAnimation");
yield return new WaitForSeconds(2f); // wait for two seconds.
Debug.Log("This happens 2 seconds later. Tada.");
}
coroutines are easy, just need to spend a little time with them.