- Home /
Increase volume when key is down and decrease volume when key is up
So i'm trying to make a very simple car engine where I press the 'W' key and the engine sound gradually increases and when I leave go of the 'W' key the volume gradually decreases. I can't seem to get it to work.
using UnityEngine;
using System.Collections;
public class CarEngine : MonoBehaviour {
float IncVolume = 0.6f;
float DecVolume = 0.6f;
float VolumeRate = 0.1f;
void Update () {
if (Input.GetKeyDown(KeyCode.W))
{
IncVolume = IncVolume + (VolumeRate * Time.deltaTime);
GetComponent<AudioSource>().enabled = !GetComponent<AudioSource>().enabled;
GetComponent<AudioSource>().volume = IncVolume;
}
if (Input.GetKeyUp(KeyCode.W))
{
DecVolume = DecVolume - (VolumeRate * Time.deltaTime);
GetComponent<AudioSource>().volume = DecVolume;
GetComponent<AudioSource>().enabled = !GetComponent<AudioSource>().enabled;
}
}
}
I have the IncVolume and DecVolume at 0.6 because that is the volume thats in the Inspecter and I want to increase and decrease the volume by 0.1 every second or so.
Answer by zharik86 · Oct 31, 2015 at 08:03 AM
Functions GetKeyDown and GetKeyUp works, when user starts pressing down or up the key, one time. I correct your code:
private int grad = 0; // add one more variable for graduation volume effect
void Update () {
if (Input.GetKeyDown(KeyCode.W)) {
grad = 1;
}
if (Input.GetKeyUp(KeyCode.W)) {
grad = -1;
}
if (grad != 0) {
this.audio.enabled = true;
this.audio. volume += grad * VolumeRate * Time.deltaTime;
if (this.audio.volume < 0.1 || this.audio.volume > 0.6) {
if (this.audio.volume < 0.1) {
this.audio.volume = 0.1f;
} else {
this.audio.volume = 0.6f;
}
grad = 0;
}
}
}
Thanks. it said that 'this.audio.enabled = true' was obselete so I had to use 'this.GetComponent().enabled = true' ins$$anonymous$$d.
Your answer
![](https://koobas.hobune.stream/wayback/20220612043347im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Audio on object plays low in unity 5 1 Answer
Unity 5 asset bundle low audio volume 0 Answers
iOS - Audio Volume Too Loud 0 Answers
Breathing volume increases as player gets more tired 0 Answers
All we need is..... Radio Gaga 1 Answer