- Home /
Unity 2D: perform action after animation is done.
Hello everyone,
I have a question regarding a throwing/shooting animation for a 2D platformer game. I have this "throw" sprite animation that I want to play when the user presses the fire button. The animation itself is such that there is an anticipation phase where the character leans back to put force behind his throw, followed by a forward motion where the character actually throws the object.
I was wondering whether it is possible to play the animation when the user presses the fire button and then only AFTER the animation has played out, create a "bullet" object that will fly through the scene. If it is possible, how would this be done in C# scripting? Is there some sort of callback mechanism I can use?
Many thanks in advance!
Answer by Denvery · Mar 27, 2014 at 09:49 PM
You can use Animation events: https://docs.unity3d.com/Documentation/Components/animeditor-AnimationEvents.html
So when your "throw" sprite animation finish, specified function is called. This function may create a bullet object etc. :)
As for me it is the most simple way.
Answer by Destran · Mar 27, 2014 at 07:51 PM
You could use a Coroutine :D
void Update()
{
if(conditions to throw are met)
{
StartCoroutine(Throw());
}
}
IEnumerator Throw()
{
animation.Play("throw");
yield return new WaitForSeconds (animation["throw"].length);
}
I think this is correct c#, but I don't actually know c# that well so... :D
I did not know about CoRoutines. I will look into it. Thanks very much!
This is incorrect! if your frame rate drops then the animation takes longer time to complete but WaitForSeconds does not depend on frame rate and it would return.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Animation callbacks and/or events? 2 Answers
Setting local position after animation is inconsistent 0 Answers
Multiple Cars not working 1 Answer
How to get the Quaternion Rotation from a Matrix4x4 2 Answers