Search Unity

Question Collect Audio Is Not Playing

Discussion in 'Audio & Video' started by Demon_xModRx, Jul 4, 2020.

  1. Demon_xModRx

    Demon_xModRx

    Joined:
    May 15, 2020
    Posts:
    3
    I'm trying to get a collect sound to play when a coin is collected. When the collect sound is in the coin prefab, the sound doesn't play, but when the collect sound is outside of the coin prefab, it does. but having the sound outside of the prefab means that I have to set the sound in every individuals coin. Any suggestions as to how I can get the audio to play with the audio source in the prefab? Here's my code:
    Code (CSharp):
    1.     public AudioSource audioSource;      
    2.     public AudioClip collect;
    3.     public float vol = 1;
    4.     void OnTriggerEnter(Collider other)
    5.     {
    6.         ScoringSystem.theScore += 1;
    7.         Destroy(gameObject);
    8.         audioSource.PlayOneShot(collect, vol);
    9.     }
    unitydfgsdg1.PNG unitydfgsdg2.PNG
     
  2. JLF

    JLF

    Joined:
    Feb 25, 2013
    Posts:
    140
    The issue is because you’re destroying the object. As soon as the object gets destroyed, so does the audio source.

    There are lots of different ways to solve this but the simplest is probably to use play clip at point.

    If you use play clip at point instead of play one shot, And maybe call it before The destroy line, this will play a sound that lasts until after the object it’s on is destroyed. It does this by making a temporary audio source so you wouldn’t need to have one on the object.

    for a more in depth description on play clip at point try my article: https://gamedevbeginner.com/how-to-play-audio-in-unity-with-examples/#clip_at_point

    hope that helps.
     
    Demon_xModRx and Sound-Master like this.