- Home /
Audio won't play when key is pressed
I'm pretty new to Unity, and I don't have much experience with scripting, so I was wondering if anyone could help with a problem I have...
I'm trying to get an audio clip to play whenever the key "f" is pressed on the keyboard, as well as an animation. Here's the code:
function Update () {
if (Input.GetKeyDown ("f")) {
animation.Play ("Flight");
audio.Play("Flight_AudioClip")
}
}
So far, the animation works absolutely fine, but the audio refuses to play, and the error box comes up with "Assets/Scripts/Flight.js(5,27): BCE0017: The best overload for the method 'UnityEngine.AudioSource.Play()' is not compatible with the argument list '(String)'."
I have no idea what this means, I've tried replacing "audio.Play" with heaps of other things, looked on the net for templates of scripts to use, but I still can't find any sort of answer...
can anyone help please? I just do not understand...
Answer by FLASHDENMARK · Jun 11, 2011 at 04:55 PM
First of all you will need to add a audio source to the gameObject that is supposed to play the audio clip.
I would do this instead:
var canPlayAudio = true;
var waitTime = 1.0; // Change this to the approximate time the audio clip takes to finish.
var MySound : AudioClip; //Drag your audio clip here in the Inspector.
function Update ()
{
AudioController();
}
function AudioController();
{
if (Input.GetKeyDown ("f") && canPlayAudio)
{
canPlayAudio = false;
animation.Play ("Flight");
audio.PlayOneShot(MySound);
yield WaitForSeconds(waitTime);
canPlayAudio = true;
}
}
Thankyou so much, it was very helpful :) I understand now...
But what about if I just want it to play once at a time, because when I press the f key several times, the noise plays over itself, like there are many instances playing in the moment. Right now, I just want the animation and audio to play once at a time, not over itself... do you know what I mean? I tried using Event.Ignore, but the error box scowled at me again...
Yes, I do understand your question. And yes I will change the script according to what you just said. :)
Answer by henry96 · Jun 11, 2011 at 03:38 PM
try to make variable on top to specify which audio!
var myaudio : AudioClip;
then in the fifth line of ur script: audio.Play (myaudio);
if it doesn't work, try
AudioSource.PlayClipAtPoint (myaudio, transform.position);
Answer by Tom 17 · Jun 11, 2011 at 03:37 PM
The thing is you're using it wrong. You need an instance of an AudioSource first, in the scripting reference this is often called audio. So audio is meant to be a variable. Please review the following pages to get an understanding of how the setup should be:
Your answer
Follow this Question
Related Questions
audio.Play not working 1 Answer
Play Oneshot Audio On Touch 0 Answers
Audio.Play() not showing up 1 Answer
how do i play a sound if i press a particular key? 2 Answers