How do I make the same keypress do different things?

So I’m using Dotween for the first time and I was trying to get it to start when “Space” gets pressed and make it stop with the same key. This seems to work but its not responsive enough.

using UnityEngine;
using System.Collections;
using DG.Tweening;

public class Keypress : MonoBehaviour
{
    public GameObject go;
    bool _isPlaying = false;

    DOTweenPath _animate;

    void Start()
    {
        _animate = go.GetComponent<DOTweenPath>();
    }

    void Update() {
        if(Input.GetKeyUp(KeyCode.Space))
        {
            if(_isPlaying == true)
            {
                StopCoroutine("StartLoop");
                StartCoroutine("StopLoop");
            }
            if(_isPlaying == false)
            {
                StartCoroutine("StartLoop");
            }
        }
    }
      
    IEnumerator StartLoop()
    {
        yield return new WaitForSeconds(.001f);
        _isPlaying = true;
        _animate.DOPlay();
    }
    IEnumerator StopLoop()
    {
        yield return new WaitForSeconds(.001f);
        _isPlaying = false;
        _animate.DOPause();
    }
}

The first one I tried is this but for some reason start and stop is trigger at the same time so it’ll start playing but won’t stop on the second space press.

using UnityEngine;
using System.Collections;
using DG.Tweening;

public class Keypress : MonoBehaviour
{
    public GameObject go;
    bool _isPlaying = false;

    DOTweenPath _animate;

    void Start()
    {
        _animate = go.GetComponent<DOTweenPath>();
    }

    void Update() {
        if(Input.GetKeyUp(KeyCode.Space))
        {
            if(_isPlaying == true)
            {
                _animate.DOPause();
                _isPlaying = false;
            }
            if(_isPlaying == false)
            {
                _animate.DOPlay();
                _isPlaying = true;
            }
        }
    }
}

You should use Input.GetKeyDown(…) instead of Up to get responsive input. GetKeyDown returns true the exact moment you press space, GetKeyUp returns true whenever you release space. Also, change line 25 to an “else”, otherwise the stuff inside those brackets will run when the first if-statement runs.

1 Like

Ah OK. Thanks a lot. It worked perfectly.