Search Unity

Using a button to toggle an animation on and off

Discussion in 'Animation' started by KardFett, Jul 13, 2021.

  1. KardFett

    KardFett

    Joined:
    Jun 8, 2021
    Posts:
    2
    Obligatory "new to Unity and scripting in general" warning.

    I'm trying to make it so that I have an alarm light that I can turn off or on when I press a UI button. I have an animation clip made that does one blinking cycle, and I have it set to loop. What I would like to do is have the animation start as not being played (it currently plays as soon as I start the game), and then when I click the UI button, have it call a function that checks if the animation is playing, starts it if it isn't, and stops it if it is. I'm okay with the script being extremely utilitarian, as you'll see from what I have so far:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class AlarmAnimation : MonoBehaviour
    6. {
    7.     public Animator anim;
    8.     public Light light;
    9.  
    10.    
    11.     public void ToggleAnimation()
    12.     {
    13.         if (anim.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.Blinking"))
    14.         {
    15.             anim.StopPlayback();
    16.             light.intensity = 0;
    17.         }
    18.  
    19.         else
    20.         {
    21.             anim.Play("Base Layer.Blinking, 0, 0");
    22.         }
    23.     }
    24. }
    I don't need it to be flexible or anything, so I just insert the animator in question using the Inspector, as well as the light that the animation clip was made for. The animation in question simply has it start at intensity 2, stay that way for 60 frames, go to intensity 0 over 1 frame, stay that way for 60 frames, and then loop back to intensity 2 as the animation loops. My goal would be that if the light was on when someone pressed the button again to stop the animation, the "light.intensity = 0" line would make it look like the animation reset.

    I'm quite sad that the legacy "Animation" class doesn't seem to work anymore. Its API has a nice .Play() and .Stop() method, whereas I can't seem to find anything in the "Animator" class to do the same thing as simply. I'd love to be able to just reset the playback state when the button is pressed while the animation is playing, but from what I can see it only has a method to reset a trigger parameter, but maybe I'm just not familiar enough with it to realize how you're supposed to accomplish something like that.

    Thanks!

    P.S. if anyone has a better idea of how to accomplish the function of turning a blinking sequence on and off using a UI button, I'm open to that to. After trying a few things, using an animation clip and trying to control that seemed like the simplest solution, as opposed to trying to create an interruptible loop within a script itself.