- Home /
Starting and stoping running script with C#
I have this code that does allow my character running animation to play continuously. What I want is for the running to only start when I press the right arrow key and stop when I release the key. I made this in C#. Any help?
using UnityEngine;
using System.Collections;
public class Animation : MonoBehaviour {
public float FPS;
private float secondsToWait;
public bool Loop;
public Texture[] frames;
private int currentFrame;
// Use this for initialization
void Start ()
{
currentFrame = 0;
secondsToWait = 1/FPS;
StartCoroutine(Animate());
}
IEnumerator Animate()
{
bool stop = false;
if(currentFrame >= frames.Length)
{
if(Loop == false)
stop = true;
else
currentFrame = 0;
}
yield return new WaitForSeconds(secondsToWait);
renderer.material.mainTexture = frames[currentFrame];
currentFrame++;
if(stop == false)
StartCoroutine(Animate());
}
}
Answer by Llama_w_2Ls · Jan 21, 2021 at 09:00 AM
First of all, you need to keep track of if the coroutine has finished running before you call it again. Then, in the update, check for key presses. For example:
bool IsPlayingAnimation;
void Update()
{
if (Input.GetKey(KeyCode.RightArrow))
if (!IsPlayingAnimation)
StartCoroutine(Animate());
}
Then, your Animate coroutine would look like:
IEnumerator Animate()
{
IsPlayingAnimation = true;
bool stop = false;
if(currentFrame >= frames.Length)
{
if(Loop == false)
stop = true;
else
currentFrame = 0;
}
yield return new WaitForSeconds(secondsToWait);
renderer.material.mainTexture = frames[currentFrame];
currentFrame++;
if(stop == false)
IsPlayingAnimation = false;
}
Since your animate method isn't looping, it shouldn't play the animation if the right arrow key isn't being pressed, I believe. @Riotgear66
Your answer
![](https://koobas.hobune.stream/wayback/20220613074739im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Running animation 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Mouse move to control the animation 1 Answer
How to fix this animator is not playing an animatorcontroller? 1 Answer