- Home /
GUI Button sound problem, don´t work
Hi i´m trying make a pause menu with gui and i want when the mouse will be on button play sound, i already have sound when clicking but not when i hover mouse on it there is my code: thanks for help
var windowPause:Rect=Rect(1000,1000,1000,1000); private var showPause:boolean;
var enter : AudioClip;
var press : AudioClip;
var buttonRect : Rect = Rect(110,120,70,30);
function Update () {
if (Input.GetButtonUp ("Pause")) {
if (showPause == true) {
showPause = false;
Time.timeScale = 1;
}
else if (showPause == false){
showPause = true;
Time.timeScale = 0;
}
}
}
function OnGUI () {
if (buttonRect.Contains(Input.mousePosition)) {
audio.PlayOneShot (enter);
}
if (showPause==true){
windowPause= GUI.Window(1, windowPause, DoMyWindowPause, "Pause");
}
}
function DoMyWindowPause () {
if (GUI.Button(Rect(110,80,70,30),"Resume")){
audio.PlayOneShot(press);
showPause = false;
Time.timeScale = 1;
}
if (GUI.Button(buttonRect,"Setting")){
audio.PlayOneShot(press);
}
if (GUI.Button(Rect(110,160,70,30),"Exit")){
audio.PlayOneShot(press);
Application.LoadLevel(0);
Time.timeScale = 1;
}
}
Answer by robertbu · Aug 10, 2014 at 04:44 AM
You have three problems here. First you are using Screen coordinates in a Rect.Contains() with a rect defined in GUI coordinates. Second, you call 'PlayOneShot()' repeatedly (every frame when the mouse is in the rect). Third, when you click the button, you are also going to evaluate to true for the 'buttonRect.Contains(). Here is a bit of untested code. You might have to go with a latching mechanism where you don't play 'enter' a second time rather than using Input.GetMouseButtonDown(0):
function OnGUI () {
if (!audio.isPlaying && buttonRect.Contains(Event.current.mousePosition) && !Input.GetMouseButtonDown(0)) {
audio.PlayOneShot (enter);
}
if (showPause==true){
windowPause= GUI.Window(1, windowPause, DoMyWindowPause, "Pause");
}
}
thanks for answer and helping, but still it isn´t work correctly, when i playing the game and with mouse move the on certain position it´s in at top right corner somewehere there, and when i reach this position the sound is playing constantly, don´t understand but thanks for help !