Unity2D Playing an Animation when my Character Jumps

hey, I am making a little platformer using Unity2D. I have a smoke animation that plays under my characters feet when I jump (pressing the spacebar). And it Sorta works, the smoke animation plays once when I press the space bar.

Right now, I just have a script that Disables the Sprite Renderer until I press “Space”. (after pressing “Space” The Sprite Renderer is enabled for a second) Then after a second (using timer) it Re-Disables the Sprite Renderer. But this only happens once. How can I fix it, so the animation plays EVERY TIME I press the spacebar?

Here is the Script for the Smoke Animation:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Sprites;

public class JumpDust : MonoBehaviour
{
    public SpriteRenderer spriteRenderer;
    public int lifeTime = 1;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        StartCoroutine(WaitThenDie());

        if (Input.GetKeyDown(KeyCode.Space))
        {
            spriteRenderer.enabled = true;
        }

        IEnumerator WaitThenDie()
        {
            yield return new WaitForSeconds(lifeTime);
            spriteRenderer.enabled = false;
        }
    }
}

Glancing at your code, you’re starting a new coroutines every frame (line 10 above).

Don’t do that.

Instead, show the sprite, then start a coroutine to shut it off… ONCE per start.

If you don’t see what I mean above, time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

Hello @Kaisukki. Just for your information, I formatted your code block for better readability, and syntax highlighting. We strongly encourage you to use the Preformatted text </> for your code-blocks in your future posts for the same reasons.
Let us know if you have any questions in Unity Discussions Feedback