- Home /
How do I play an animation once on button click?
I am trying to make an animation play every time a button is pressed, but I can’t figure out how to make it work. It either plays multiple times or it just plays once and doesn’t work the next time I press the button. How can I fix this using C#?
Here's my code. When I press the button the animation just plays on an endless loop.
[SerializeField] private Animator animationController;
public void CorrectAnswer () {
if (currentLevel + 1 != Levels.Length) {
Levels[currentLevel].SetActive(false);
currentLevel++;
Levels[currentLevel].SetActive(true);
}
score += 1;
scoreText.text = score.ToString();
if (score <= 0) {score = 0;}
animationController.SetBool("playAnimation", true);
}
Here's my animator. I have it so that it the play animation bool is true, it goes from its default state to the animation, but if it is false it goes back to its default state.
You need to provide a detailed description of your animator and screenshots of it (edit your question to add those details, thanks)
Answer by Zaeran · Dec 15, 2021 at 06:52 AM
Use a Trigger variable in your Animator Controller instead of a Bool. Go from Default State to 1point on Trigger, go from 1point to DefaultState when the animation finishes
How do I make it go to the default when the animation is done?
Basically the same way you do now, but instead of doing it based on the variable, you do it based on time