- Home /
Sound on keypress, not working
No Javascript experience here so bare with me. I have a spacecraft, and need it to make an acceleration sound everytime it accelerates. The accelerate key is "z", but I want the sound to stop when you let go of the "z" key.
So here's the code I have but it's not working, there is no sound whatsoever:
var sound : AudioClip;
function Update()
{
if (Input.GetKeyDown ("z"))
{
audio.PlayOneShot(sound);
}
else
{
audio.PlayOneShot(sound);
audio.Pause();
}
}
I attached an Audio Source to a empty game object, then applied the script to the empty game object with the correct sound specified. One other issue is the spacecraft can also be controlled by a joystick. The acceleration key is "joystick button 1", how can I trigger that sound by both the keypress AND joystick button? Any help would be very much appreciated.
Are you asigning your sound var to the AudioClip in the empty game object you mention? You should have something like:
function Start()
{
var soundGO = GameObject.Find("NameOfSoundGameObject");
sound = soundGO.GetComponent("AudioSource").AudioClip;
}
in your script.
Answer by zharik86 · Sep 10, 2014 at 06:54 AM
The function GetKeyDown() works only once after button is pessing. Besides in your condition you always stop audio playback by the function Pause(). I will write a small script:
var sound : AudioClip;
private var myAP: boolean;
function Start() {
myAP = false;
}
function Update() {
//Change function GetKeyDown() on GetKey()
if (Input.GetKey (KeyCode.Z) || Input.GetKey(KeyCode.JoystickButton1)) {
if(!myAP) {
myAP = true;
audio.PlayOneShot(sound, 1.0);
}
} else {
myAP = false;
audio.Pause();
}
}
I hope that it will help you.
Thanks very much! This works very nicely and there's no weird sound issues/popping, however I need the sound to stop once the key is not pressed. Is this possible?
Update: Works perfectly now, I simply changed audio.Pause(); to audio.Stop();
full code
var sound : AudioClip;
private var myAP: boolean;
function Start() {
myAP = false;
}
function Update() {
//Change function Get$$anonymous$$eyDown() on Get$$anonymous$$ey()
if (Input.Get$$anonymous$$ey ($$anonymous$$eyCode.Z) || Input.Get$$anonymous$$ey($$anonymous$$eyCode.JoystickButton1)) {
if(!myAP) {
myAP = true;
audio.PlayOneShot(sound, 1.0);
}
} else {
myAP = false;
audio.Stop();
}
}
Thanks for your help.
Answer by 767_2 · Sep 10, 2014 at 08:43 AM
Update()
executes every frame so your sound plays but on the next frame it will pause because you just set it like that audio.Pause();
so that's how you never here anything