- Home /
How do I play a sound when pressing the W key, and when I stop pressing the W key, the sound stops?
I'm trying to play a sound when a vehicle is moving, so when I press the W key, it moves, and it plays the sound. But as soon as I release the W key, the sound continues to play, it doesn't stop instantly. I'd like for it to play an Idle sound when the vehicle isn't moving, an Shifting sound when W is pressed, and Reversing sound when the car is going backwards (not if S is pressed to slow the car down) and a braking sound when Spacebar is pressed. Plus, for all of these (Minus the Spacebar/brake) I would like it to play an decelerating sound when these keys aren't being pressed. Is this possible? If so, what is the code? How do I fix the W sound?? Please Help!
Script:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayonW : MonoBehaviour {
public AudioSource someSound;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.W)) {
someSound.Play();
if (Input.GetKeyUp(KeyCode.W)) {
someSound.Stop();
}
}
}
}
Answer by TanselAltinel · May 07, 2018 at 12:53 PM
You should put your braces correctly for your script to work. Also, don't call Play each frame if the audio source is already playing:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayonW : MonoBehaviour {
public AudioSource someSound;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.W)) {
if(!someSound.isPlaying) {
someSound.Play();
}
}
if (Input.GetKeyUp(KeyCode.W)) {
someSound.Stop();
}
}
}
To your other question: Either have different Audio Sources for your each move set (move forward, reverse, break etc.) and play / stop them like this code, or have different clips and change the clip and see what clip is playing to play stop it at specific key presses.
hey, may i ask, if i want every key that i press to make noise. i am currently making a typing game and i want a keyboard typing sound fx. what code should i change
I'm not sure what you're trying to achieve, if you want different sound for each key, you can use this and replicate. If you want to use the same sound for all kind of inputs, you can use Input.anyKey.
Answer by nomanbangash97 · Aug 08, 2021 at 06:15 AM
public AudioSource audioSource;
// Use this for initialization
void Start () { audioSource = GetComponent(); }
// Update is called once per frame
void Update () { if (Input.GetKeyDown(KeyCode.W)) { audioSource.Play(); }
if (Input.GetKeyUp(KeyCode.W))
{
audioSource.Stop();
}
}
Your answer
Follow this Question
Related Questions
5.1 Channels is backwards in unity (non 3D) 0 Answers
Audio Settings Menu 2 Answers
play sound when moving stop sound when not 1 Answer
Stop sound on input.getkeyup 1 Answer