Question by
Cluelessguy · Apr 13, 2016 at 10:12 PM ·
scripting problemaudiodelaynotworking
Script plays sound at incorrect time
I wrote a script that plays a sound after 3 seconds and set it to play on awake which made it play right away. So I tried unchecking Play on awake it doesn't play at all. Where is the error?
using UnityEngine;
using System.Collections;
public class Gunshot : MonoBehaviour
{
public AudioClip Gun;
private float volLowRange = .5f;
private float volHighRange = 1.0f;
private AudioSource source;
public float timeLeft = 5.0f;
void Awake()
{
source = GetComponent<AudioSource>();
}
public void Update()
{
timeLeft -= Time.deltaTime;
if (timeLeft <= 0.0f)
{
float vol = Random.Range(volLowRange, volHighRange);
source.PlayOneShot(Gun, vol);
}
}
}
Comment
Answer by TBruce · Apr 13, 2016 at 11:09 PM
@Cluelessguy This should fix your problem. I would just like to note that timeLeft is set to 5 seconds and not 3.
using UnityEngine; using System.Collections;
public class Gunshot : MonoBehaviour { public AudioClip Gun;
private float volLowRange = .5f;
private float volHighRange = 1.0f;
private AudioSource source;
public float timeLeft = 5.0f;
void Awake()
{
source = GetComponent<AudioSource>();
if (audioSource == null)
{ // if AudioSource is missing
Debug.LogWarning("AudioSource component missing from this gameobject. Adding one.");
// let's just add the AudioSource component dynamically
source = gameObject.AddComponent<AudioSource>(timeLeft);
}
if (Gun != null)
{
StartCoroutine(PlaySoundAfterDelay());
}
}
IEnumerator PlaySoundAfterDelay(float delay)
{
yield return new WaitForSeconds(delay);
source.PlayOneShot(Gun, vol);
}
}
@Cluelessguy $$anonymous$$y apologies. This is what your script should have been
using UnityEngine;
using System.Collections;
public class Gunshot : $$anonymous$$onoBehaviour
{
public AudioClip Gun;
private float volLowRange = .5f;
private float volHighRange = 1.0f;
private AudioSource source;
public float timeLeft = 5.0f;
void Awake()
{
source = GetComponent<AudioSource>();
if (source == null)
{ // if AudioSource is missing
Debug.LogWarning("AudioSource component missing from this gameobject. Adding one.");
// let's just add the AudioSource component dynamically
source = gameObject.AddComponent<AudioSource>();
}
if (Gun != null)
{
StartCoroutine(PlaySoundAfterDelay(timeLeft));
}
}
IEnumerator PlaySoundAfterDelay(float delay)
{
yield return new WaitForSeconds(delay);
float vol = Random.Range(volLowRange, volHighRange);
source.PlayOneShot(Gun, vol);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612074805im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Question on Audio? 1 Answer
Help with script for Main Menu? 1 Answer
Ubuntu 16.04 No audio 1 Answer
AudioSource dissappears in variable window on Play 2 Answers