Question by
Luis-Neves · Feb 03, 2017 at 09:21 PM ·
c#audiosourcebooleanif-statementsupdate function
AudioSource in Update
Hello! I'm trying to make an AudioSource play when a boolean is true. Problem is, it plays when set to false instead of true like it's supposed to, except when the game is initially started.
using UnityEngine;
using System.Collections;
public class Radio : MonoBehaviour {
public AudioSource speaker;
public bool switchedOn;
// Plays at false for some reason.
void Update ()
{
if (switchedOn == true) {
speaker.Play ();
}
}
Comment
Answer by HenryStrattonFW · Feb 04, 2017 at 01:25 PM
First thing is to make sure that your AudioSource component is not set to "Play on Awake" secondly, Play() will try to start the audiosources clip, so calling it each frame as you are here would keep restarting it over and over, which is likely why you only hear it play once switchedOn is false and you stop calling Play. Try this.
using UnityEngine;
using System.Collections;
public class Radio : MonoBehaviour
{
public AudioSource speaker;
public bool switchedOn;
void Update()
{
if (switchedOn == true && speaker.isPlaying == false)
{
speaker.Play();
}
else if (switchedOn == false && speaker.isPlaying == true)
{
speaker.Stop();
}
}
}