- Home /
Play Audio Once if Bool==True
I'm trying to get an object to play a sound once when a certain bool is set to "true." The problem with this is that, if I have it play if bool==true, it will play every frame that said bool==true. How can I work around this?
void Update () {
if (outage == true) {
PowerSound ();
}
}
void PowerSound(){
AudioSource outage = GetComponent<AudioSource>();
outage.Play();
}
Set it false after you check its true so like
if (outage == true) {
outage =! outage;
PowerSound ();
}
Answer by Ginxx009 · Dec 08, 2017 at 03:51 AM
When you want an audio to be played only once then go for PlayOneShot
It can be like this in your code:
public AudioClip impact;
AudioSource audioSource;
void Update(){
if(outage == true){
PowerSound();
}
}
void PowerSound(){
audioSource = GetComponent<AudioSource>();
audioSource.PlayOneShot(impact, 0.7F);
}
Answer by RoyalAllen · Jul 28, 2018 at 04:03 AM
Hey, I found a workaround with this. Create a child GameObject(Add an Audiosource and insert your clip) and set it inactive and then when the bool is True, set the GameObject Active. Make Sure that play on awake is checked. By doing this way it prevents infinity playing the audio! @Arctic_Fletcher
Example
public GameObject TurnONThis;
void Start()
{TurnONThisGameObject.SetActive(false);}
void Update()
{
If(YouWin==True)
{
TurnONThis.SetActive(true);
}