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 :frowning: What is my mistake? Thanks!

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();
}

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();
    }
}