Problems with Image.overrideSprite

Hi,

I wanted to make a button Play/Pause to play an audio track on my app. Pressing the button would swap the sprites I use for Play and Pause. I made the following script for that :

    	private int cpt = 0;
    	public Button button;
    	public Sprite swapSprite;
    
    
    	public void Play (AudioClip myaudio)
    	{
    		if (cpt % 2 == 0) {
    			audio.Play ();
    		} else {
    			audio.Pause ();
    			button.image.overrideSprite = swapSprite;
    
    		}
    		cpt = cpt + 1;
    				
    	}

The swap works fine, except when I drag the mouse away from the button. When I pause the audio, the sprite “Pause” appears. But if I drag the mouse away from the button, the sprite “Play” appears (and of course the audio is still paused).

Anyone knows why it would do that? I checked the Unity page of overrideSprite, but it does not give so much information.

Thanks a lot for your help!

Instead of using your counter, how about using the audio state as the control for the toggle?

if (!audio.isPlaying)
{
  audio.Play(); 
  // set sprite to "pause"
}
else
{
  audio.Pause();
  // set sprite to "play"
}

Make sure you call your function only on button click. This should handle things like the user dragging the mouse off the button - the only time the button functionality should execute is when the user actually clicks the button.

I like using bools better

         private bool soundOn = true;
         public Button button;
         public Sprite onSprite;
         public Sprite offSprite;
     
     
         public void Play (AudioClip myaudio)
         {
             if (!soundOn) {
                 audio.Play ();
                 button.image.overrideSprite = onSprite;
                 soundOn = true;
             } else {
                 audio.Pause ();
                 button.image.overrideSprite = offSprite;
                 soundOn = false;
             }
                     
         }