Hey everyone i have a problem,in my 2d game i don’t get any console errors but my audio won’t play.Here is my script
public float timer = 3f;
public AudioClip song;
void Update () {
timer -= Time.deltaTime;
}
if (timer <= 0) {
OnTimerDone ();
}
public void OnTimerDone()
{
GetComponent ().clip = song;
GetComponent<AudioSource> ().Play ();
}
Considering you have assigned something to “song” variable and you got AudioSource component on your object that contains that script provided by you - your line #22 is wrong as well as you have bracket misplacement, let me give you corrected version:
public float timer = 3f;
public AudioClip song;
void Update()
{
timer -= Time.deltaTime;
if (timer <= 0)
{
OnTimerDone();
}
}
public void OnTimerDone()
{
AudioSource aSrc = GetComponent<AudioSource>();
aSrc.clip = song;
aSrc.Play();
}
Also if your AudioSource component itself isn’t being replaced or added to object in runtime and you will “refresh” timer so that OnTimerDone will be called not only once then you should also consider moving your GetComponent line outside of loop, e.g. something like that:
public float timer = 3f;
public AudioClip song;
private AudioSource aSrc;
private void Awake()
{
aSrc = GetComponent<AudioSource>();
}
void Update()
{
timer -= Time.deltaTime;
if (timer <= 0)
{
OnTimerDone();
}
}
public void OnTimerDone()
{
aSrc.clip = song;
aSrc.Play();
}
P.S. Also if your song variable won’t change as well and you do refresh the timer then you could also move the line aSrc.clip = song; out of the loop as well (just for the sake of completeness).
Click add component in your audio source’s object then click audio > audio listener
Audio source,Audio listener,Script should all be in the same gameobject
Hope it works