Audio Question

I am trying to bring up a gui button when I enter a trigger, and that works fine. However, I want to make the button play a song if clicked. The song does not play however, it will start to play when I hit the pause and play buttons to start and stop the scene itself. Any help would be appreciated :slight_smile: Here is the code I have so far;

var source1 = AudioSource

if (doButtons)

	{

if (GUI.Button(Rect(10,10,50,50),btnTexture))

if (GUI.Button(Rect(10,70,50,30),"Play")

source1.audio.Play();

}

}

function OnTriggerEnter( other :Collider)

{

	doButtons = true;

}

That’s an odd way of making buttons. You are making two buttons and both need to be hit on the same frame. If you want one button with a texture that also says Play on it, either paint Play on the texture, or use GUIStyle. Anyway, try taking one of those out and see if that helps.

@DaveA is right: the two buttons make no sense, since you should press the texture button to make the Play button appear, then press this one to play the sound. Furthermore, your button code must be inside a OnGUI function to work. Other points:

  • source1 is an AudioSource, thus you don’t need the audio variable;

  • only call Play() if the sound isn’t already playing;

  • uncheck Play On Awake, or the sound will play any time you run your game.

The fixed code is:

var source1 = AudioSource;

function OnGUI(){
  if (doButtons){
    if (GUI.Button(Rect(10,70,50,30),"Play"){
      // only call Play if the sound isn't already playing:
      if (!source1.isPlaying) source1.Play();
    }
  }
}

function OnTriggerEnter( other :Collider){
    doButtons = true;
}