c# How to delay code for animator animation to finish
I have been stuck for a few days, and my searches through google and here haven't returned what I was looking for. Here is my situation:
When the player hits the "1" key, the hero character will perform an attack. I set a bool to make sure the attack can't be repeated in the time window. I set a trigger for the animation to occur, and it does, that all works fine. My issue is that I have no idea how to wait for this animation to finish.
I've tried (horribly) to use Coroutines, but when I try something to use the animator.GetCurrentAnimatorStateInfo(0).normalized time for a delay, I run into the issue that the animation I want to delay by hasn't started playing yet, because its on the same frame. I feel like it maybe a problem with how my code is structured.
If anyone could point me in the right direction, I would really appreciate the assistance.
The code:
void Update()
{
HandlePlayerInput();
}
private void HandlePlayerInput()
{
if (isPerformingAction == false)
{
if (Input.GetKeyDown("1"))
{
Attack();
}
}
}
private void Attack()
{
isPerformingAction = true;
PerformAttack();
if (FoesAreDefeated())
{
BattleWon();
}
EndCharacterTurn();
}
private void PerformBasicAction()
{
CurrentHero.animator.SetTrigger("Attack");
**//DELAY HERE USING COROUTINE?**
CalculateDamage();
}
Do you actually want to execute some code once the animation is finished?
I will want to execute some other things once it's done, yes.
Answer by BaldBeardedMonk · Apr 19, 2017 at 05:03 PM
Okay so here are the steps.
Create a function in any of the script which is attached to the gameobject which has the animation.
Open Window-> Animation and find the animation from the drop down. it will have keyframes. At the end Right click -> Add animation event . select the function you need to call. (remembers its inside Animation and not Animator
For this to work, the animation should not be read only. if it is read-only. duplicate it using Ctrl+D and replace the original animation in the Animator with the duplicated animation. (This will allow you to edit and add an event in the keyframe)
Would be nice if you mark it as answered. So that this can easily be visible for future references for anyone :)
Answer by SrGonzalez · Apr 19, 2017 at 04:42 PM
maybe you are interested in delay a certain type of seconds befor executing a command? here you have a vit of code:
void Update()
{
StartCoroutine(Warning());
}
IEnumerator Warning()
{
yield return new WaitForSeconds(2); //anything after this line is going to be called after 2 seconds
//here goes your code
}
Your answer
Follow this Question
Related Questions
How to get a for loop to run once per coroutine? 0 Answers
Coroutine Not Starting - Crashes Instead? 1 Answer
Trying to move buttons via Coroutine and transform.Translate 0 Answers
How to get a for loop to run once per coroutine? 1 Answer
Coroutine WaitForSeconds ignoring StopAllCoroutines... How can I do it? 0 Answers