- Home /
How to add sound to when a key is pressed
I already searched it on google, and couldn't find anything that could help me out. I want to make it so when I press the 'F' key it gives a sound. How can I make that.
-Chris
Answer by rutter · Oct 17, 2013 at 10:30 AM
Let's assume that you've already imported an AudioClip and attached an AudioSource to a GameObject. If not, check through the manual.
Let's make a quick class in C#:
[RequireComponent(typeof(AudioSource))]
public class PlaySoundF : MonoBehaviour {
void Update() {
if (Input.GetKeyDown(KeyCode.F)) {
audio.Play();
}
}
}
After we save the script, we can drag it onto an object in the scene, set up the corresponding AudioSource, and see if it works.
Scripting reference pages:
If you find all of this terribly confusing, now is a good time to look up a good "getting started scripting in Unity" tutorial.
does it matter if this is in C#, since all my other scripts are in Java.
no this code will work even if your other scripts are java
it'll still go through the update function every frame normally.
I tried it but I got this error: The type or namespace name `$$anonymous$$onoBehaviour' could not be found. Are you missing a using directive or an assembly reference?
This is my C# code, did I forget to add something, or wasn't I suspose to delete the codes that were already in the default C# script?
[RequireComponent(typeof(AudioSource))] public class PlaySoundF : $$anonymous$$onoBehaviour { void Update() { if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.F)) { audio.Play(); } } }
Your answer

Follow this Question
Related Questions
Problem With Walking Sounds 1 Answer
play car engine sound only when W key is pressed down? 0 Answers
Walking sound Script returns with Error: BCE0077 2 Answers
Sound stop on iphone5 and iphone5s with ios7 1 Answer
Sound not working? 1 Answer