- Home /
How to properly detect the end time of an Animation which wait for the end of the previous one ?
Hello everyone,
I already tried to post a similar question, but I had no answer so far, and I'm quite sure it's because it is a way too complex for what it is.
So I'll try to make very simpler and clearer.
Project : The main goal is to create a system where a NPC have some tasks, and each one of them have 1/ a location (the NPC will walk there then continue) 2/ a specific animation (launched after the destination is reached). I want to synchronize the animation and the action : launch a specific method once the animation is ended. And finally, I want the NPC to wait the end of the "Walking" animation before launching the animation of the task.
Problem : I'm looking for a good design for this. I've been on it for a long time now, and I just can't find something even though it seems like a very basic problem. I tried to lock the completion of the task with this chunck of code, but for some reasons it don't fit perfectly with the end of an animation...
{
float currentAnimLenght = _npcAnimator.GetCurrentAnimatorStateInfo(0).length;
float normalizedTime = _npcAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime;
float normalizedTimeInCurrentLoop = normalizedTime - Mathf.Floor(normalizedTime);
// Wait that the moving animation is ended
yield return new WaitForSeconds(currentAnimLenght - normalizedTimeInCurrentLoop);
// Set Trigger to launch the task animation, then wait until its end
_npcAnimator.SetTrigger(name);
yield return new WaitForSeconds(_animClipLenght[name]);
// This boolean prevent the NPC to do next tasks until this one is done
isAnimLaunched = false;
yield return null;
}
Can you please help me ? Do you have any "classic" method, a previous topic or a YT video that shows a great way of doing this ?
I will just preface this by saying that I absolutely despise this way of doing stuff with animation, but sometimes there is just no choice.
You can add events to animations! Link below is for 2020.3, but they've been around for ages, so don't worry if you work on older version. You won't have all those fancy options tho, only method name, no parameters, but it should be good enough for your use case.
Answer by ARobbins67 · Mar 12, 2021 at 09:57 PM
Hi,
Have you looked into animation events? They basically allow you to call some code at a certain frame in the animation, so you could put an event at the animation frame where you want the action to happen. I put a link below for more info. Hope this helps!
https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html
Your answer
Follow this Question
Related Questions
How to create animations that can be edited with scripts in runtime? 1 Answer
Animator and Scripting problems. Help !! 1 Answer
Character Animator controller/movement 1 Answer
Is there a new retargetting system for the animation in 5.5? 1 Answer
2 problems with new animation / animator,2 problems with animation 0 Answers