#Hold InPut

1 messages · Page 1 of 1 (latest)

prime bay
#

Hi i wanna when the player HOLD E open a door but my code not working because if the player press E (not holding) the door will open

[SerializeField] int time;

void Update ()
{
if (Input.GetKeyDown(KeyCode.E)) StartCoroutine(Action());
if (Input.GetKeyUp(KeyCode.E)) StopCoroutine(Action());
}

IEnumerator Action ()
{
yield return new WaitForSeconds(time);

// here my code

}

mystic ginkgo
#
[SerializeField] int time;
private bool _canOpen;
void Update ()
{
    if (Input.GetKeyDown(KeyCode.E)) StartCoroutine(Action());
    if (Input.GetKeyUp(KeyCode.E))
      if(!_canOpen) 
        StopAllCoroutines(); 
      else {_canOpen = false; ... door code}
}

IEnumerator Action ()
{
    yield return new WaitForSeconds(time);
  _canOpen = true;
}```
muted ravine
muted ravine
# prime bay Hi i wanna when the player HOLD E open a door but my code not working because if...

This is not how stopping coroutines works.
The way you implemented it, the coroutine will always execute if the player taps the key; you've essentially just delayed the response.

What you want to be doing, is cache the Coroutine instance returned by StartCoroutine, and pass that into StopCoroutine: ```cs
private Coroutine actionCoroutine;

private void Update () {
if (Input.GetKeyDown(...)) {
StopActionCoroutine();
actionCoroutine = StartCoroutine (Action());
}
if (Input.GetKeyUp(...)) {
StopActionCoroutine();
}
}

private IEnumerator Action() {
yield return new WaitForSeconds(...);

// do stuff
}

private void StopActionCoroutine () {
if (actionCoroutine != null) {
StopCoroutine (actionCoroutine);
}
}```

mystic ginkgo
prime bay
#

Nice it’s working good but how can I add a sound when the player holding E?

prime bay
muted ravine
#

Call Play() on an audio source when the coroutine starts, and Stop() when the coroutine stops 🤷‍♂️