- Home /
Play sound, while press any key
Hi, guys! I tried to make script which would make a sound after pressing any buttons.
I tried this script:
using UnityEngine;
using System.Collections;
public class KeyPressSound : MonoBehaviour {
void onGUI() {
Event e = Event.current;
if (e.isKey)
Debug.Log("Detected a keyboard event!" + e);
audio.Play();
}
void Update(){
}
}
But it doesn't make a sound :( What is my mistake? Thanks!
Answer by robertbu · Jan 09, 2013 at 11:11 PM
You are calling audio.Play() at each frame, so the audio is being reset to the beginning at each frame so never has a chance to play. Change the code:
if (e.isKey) {
Debug.Log("Detected a keyboard event!" + e);
audio.Play();
}
I changed script:
using UnityEngine; using System.Collections;
public class $$anonymous$$eyPressSound : $$anonymous$$onoBehaviour {
void onGUI() {
if (e.is$$anonymous$$ey) {
Debug.Log("Detected a keyboard event!" + e);
audio.Play();
}
}
}
And now the error: Assets/Scripts/$$anonymous$$eyPressSound.cs(7,10): error CS0103: The name `e' does not exist in the current context
You deleted the variable. Add
Event e = Event.current;
just above the if block.
Answer by underfranks · Jan 11, 2013 at 11:16 AM
Looks like there is a typo in the function name. It should be "OnGUI" not "onGUI".
void OnGUI() {
Event e = Event.current;
if (e.isKey) {
Debug.Log("Detected a keyboard event!" + e);
audio.Play();
}
}
Your answer
Follow this Question
Related Questions
Unity only one sound works per scene 2 Answers
Play sound on button press? 1 Answer