- Home /
Play Sound on GetKey
I want to be able to play a looped sound while I keep a key pressed:
if (Input.GetKey (KeyCode.Delete))
{
object.transform.Rotate(0, -15*Time.deltaTime, 0);
//play sound while object is rotated
audio.clip = mySound;
audio.Play();
Debug.Log("Play sound");
}
And I got the exact opposite of the desired effect. Sound is played only after I press and release the first time my key. On press again, it's quiet. On release, it's looping nicely. Also, I can't use KeyDown (which makes the sound work properly) or it will nullify the transform of the object.
Please explain your last sentence. It alone out of your entire question makes no sense. What about using $$anonymous$$eyDown will nullify the transform of the object? How does that work?
Sorry - here's what happens - on Geet$$anonymous$$eyDown the sound works fine - but the object is transformed only on the frame I pressed the key - hence it barely moves an inch as opposed to move or rotate in this case as long as I keep the key pressed. What if I replace Time.deltaTime with something else?
Basically this happens because every frame you are restarting the sound- and so it never gets a chance to play! See my answer for more details.
Answer by syclamoth · Nov 11, 2011 at 01:16 PM
That's not what I'd call 'nullifying the transform'. In any case that's easy- split it off into three actions!
if (Input.GetKey (KeyCode.Delete))
{
object.transform.Rotate(0, -15*Time.deltaTime, 0);
}
if (Input.GetKeyDown (KeyCode.Delete))
{
//play sound while object is rotated
audio.clip = mySound;
audio.Play();
Debug.Log("Play sound");
}
if (Input.GetKeyUp (KeyCode.Delete))
{
audio.Stop();
Debug.Log("Stop sound");
}
@syclamoth Hi, what type
is audio
? Is it of type AudioClip
? Because both clip
and Play
do not exist under audioClip
(C#).
Answer by CallToAdventure · Nov 11, 2011 at 01:51 PM
Thank you Sir!
did I just use an answer field to post a comment? :D need better comment buttons here :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613041210im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Morse - beeps not clear 0 Answers
Multiple sound sources of the same sound file 1 Answer
Getting sound trigger to work 1 Answer