Sprite Animation via script C#
Hi everyone!
I have this script from duckbridge
 using UnityEngine;
 
 public class Sword : MonoBehaviour {
 
     float FPS = 35f;
     public Sprite[] frames;
     private SpriteRenderer outputRenderer;
     private float secondsToWait;
 
     private int currentFrame;
     private bool stopped = false;
 
     public void Awake () {
 
         outputRenderer = this.GetComponent<SpriteRenderer>();
 
         currentFrame = 0;
         if(FPS > 0) 
             secondsToWait = 1/FPS;
         else 
             secondsToWait = 0f;
     }
 
     public void Play(bool reset = false) {
 
         if(reset) {
             currentFrame = 0;
         }
 
         stopped = false;
         outputRenderer.enabled = true;
 
         if(frames.Length > 1) {
             Animate();
         } else if(frames.Length > 0) {
             outputRenderer.sprite = frames[0];
         }
     }
 
     public virtual void Animate() {
         CancelInvoke("Animate");
         if(currentFrame >= frames.Length) {
             
                 currentFrame = 0;
 
         }
 
         outputRenderer.sprite = frames[currentFrame];
 
         if(!stopped) {
             currentFrame++;
         }
 
         if(!stopped && secondsToWait > 0) {
             Invoke("Animate", secondsToWait);
         }
     }
 
     void Update () {
     
         if (Input.GetKeyDown (KeyCode.Space)) {
         
             Play ();
 
         }
     }
 }
 
               as you can see in the end I added Update, so when i press space the animation plays. the problem is that it loops, and I don't want that how can I change it? Thanks & sorry for bad engllish
Answer by Bill9009 · May 24, 2017 at 09:27 PM
I would recommend using Unity's built in Animator. Link to Tutorial. If you want to use this code however, Then do:
 bool f = true;
 void Update () {
 if (Input.GetKeyDown (KeyCode.Space) && f) {
 Play ();
 f = false;
 }
 
               But, it would be smarter to use the animator.
Your answer
 
             Follow this Question
Related Questions
How to create a sprite animation template? 0 Answers
Animation with different behaviors for different directions. 1 Answer
Animation events not working for my sprite animation 0 Answers
Unity 2D: Game freezes after the first frame of a particular animation 1 Answer
Unity2D animation and sprite layout 0 Answers