How to play only one sound at the same time ?

Im creating a soundboard game and i want to play only one sound at the same time. When I press another button I want to stop the first sound and play second sound. What should I do ?
Sorry for my English :confused:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

[RequireComponent(typeof(Button))]
public class ClickSound : MonoBehaviour {


	public AudioClip sound;

	private Button button { get { return GetComponent<Button> (); } }
	private AudioSource source { get { return GetComponent<AudioSource> (); } }




	void Start ()
	{
		gameObject.AddComponent<AudioSource> ();
		source.clip = sound;
		source.playOnAwake = false;


		button.onClick.AddListener (() => PlaySound ());
	}

	void PlaySound ()
	{
		source.PlayOneShot (sound);
	}
}

All you need to do is swap “PlayOneShot” for “Play”, and also it’s probably best to put a source.Stop() call just before you set the clip on the source, so basically the logic flows as such:

  • Stop sound currently playing.
  • Change to new sound.
  • Play new sound.

EDIT:
Had another read over your code and realised I missed the point a bit first time around (sorry about that) I’m assuming that this component you’ve written is on all of your buttons. In that case I would suggest you store the currently playing button in a static variable when you play a sound. That way when you try to press a new button, you can check this value, ensure the sound on it is stopped, and then play your new sound before then setting that button as the last active button. Here’s some code that should do the trick.

    private static ClickSound lastClickSound;

    void PlaySound()
    {
        if (lastClickSound != null && lastClickSound.source != null)
        {
            lastClickSound.source.Stop();
        }
        source.Play();
        lastClickSound = this;
    }