Search Unity

Toggle Sound On/Off

Discussion in 'Scripting' started by Gradius, Jan 20, 2011.

  1. Gradius

    Gradius

    Joined:
    Jan 18, 2011
    Posts:
    6
    Hi there All,

    I did a quick search but couldn't find anything that looked like it was what I needed, but here we go...

    I'm trying to make a GUI.Button that when clicked, disables the Audio.Listener on the Main Camera. I think I understand the basic fundamentals of the code that I need. Here is what I think it should look like, though I know it is incorrect.

    // Start

    var AudioListener : boolean;

    function OnGUI()
    {
    var buttonName:String = "Sound is ";

    if(GUI.Button(Rect(0, 0, 200, 100), "Sound On/Off"))
    {
    if (AudioListener == true)
    AudioListener = false;
    else
    AudioListener = true;
    }

    }

    // End

    When I attach this script to the Main Camera and manually remove the default Audio Listener, I can run the program. And when the GUI button is pressed I can see the check-box checking and unchecking in the inspector but I get no sound. If I click on components and re-add the Audio->Audio Listener sounds are back but cannot be disabled.

    Perhaps I"m not too far off but maybe using the wrong variables/calls?

    Thanks in advance!
     
  2. Gradius

    Gradius

    Joined:
    Jan 18, 2011
    Posts:
    6
    I was able to fix this issue by using:

    //Start

    function OnGUI()
    {
    var buttonName:String = "Sound is ";
    var volume : float;

    if(GUI.Button(Rect(0, 0, 100, 25), "Sound On/Off"))
    {
    if (audio.volume == 1.0)
    audio.volume = 0.0;
    else
    audio.volume = 1.0;
    }

    }

    //Finish