- Home /
When I press my second button audio is still playing from the first button. How to stop the audio from first button when I click second button?
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Button))]
public class ButtonSound : MonoBehaviour
{
public AudioClip sound;
private Button button { get { return GetComponent<Button>(); } }
private AudioSource source { get { return GetComponent<AudioSource>(); } }
// Start is called before the first frame update
void Start()
{
gameObject.AddComponent<AudioSource>();
source.clip = sound;
source.playOnAwake = false;
button.onClick.AddListener(() => PlaySound());
}
// Update is called once per frame
void PlaySound()
{
source.Play();
}
}
In Audio Source Loop is true;
If you want it to start over every time, what most people do is play one shot, it works like this.
public AudioClip clip;
public AudioSource source;
void PlaySound()
{
source.PlayOneShot(clip);
}
This way the source can be used for all UI sounds and you just add the play clips the script or an audiomanager and use the same source for any UI audio, heck it can be your BG music source.
A more extendable way would be
public AudioClip[] clips;
public AudioSource source;
public void PlayUISound(int id)
{
source.PlayOneShot(clips[id]);
}
@RobAnthem I have tried the first one but it does not work and I want to stop the sound of the first button when I click on the second button, but when I click on the second button, first sound play continuously and second button sound also plays.
Answer by tormentoarmagedoom · May 25, 2019 at 07:51 PM
Hello.
tried this?
void PlaySound()
{
source.Stop();
source.Play();
}
Bye!
Your answer
Follow this Question
Related Questions
Audio source playing different soundfiles 0 Answers
mute/un-mute 1 Answer
simulate DJ scratching 0 Answers
AudioSource pitch measurement unit 1 Answer
Random, 3d sound. 1 Answer