Search Unity

Question Calling source.Stop() is stopping my PlayOneShot() clip

Discussion in 'Audio & Video' started by angeldevelopment, Jan 26, 2024.

  1. angeldevelopment

    angeldevelopment

    Joined:
    Sep 28, 2022
    Posts:
    247
    I have a door script, when the door is opened from closed I call: PlayOneShot(openFromClosedSound);
    I have another method, that stops the source, switched the clips, and then plays it again, for when the door is opening/closing.

    I had thought that calling Stop() did not effect sounds played with one shot, I thought they were play and forget, but when I call this method right after calling PlayOneShot, it does not play the one shot sound.

    When I comment out my method, the sound is played as expected.

    Code (CSharp):
    1.     void PlayClip(AudioClip clip) {
    2.         // abort if no source
    3.         if (audioSource == null) return;
    4.         // stop and set new clip
    5.         audioSource.Stop();
    6.         audioSource.clip = clip;
    7.         // set random pitch if fluctuation is set
    8.         if (globalPitchFluctuation != 0) {
    9.             float currentPitch = audioSource.pitch;
    10.             audioSource.pitch = Random.Range(currentPitch - globalPitchFluctuation, currentPitch + globalPitchFluctuation);
    11.         }
    12.         audioSource.Play();
    13.     }
     
  2. angeldevelopment

    angeldevelopment

    Joined:
    Sep 28, 2022
    Posts:
    247
    bumpity bump
     
  3. SeventhString

    SeventhString

    Unity Technologies

    Joined:
    Jan 12, 2023
    Posts:
    407
    Hi @angeldevelopment

    So `PlayOneShot` does have this "fire-and-forget" quality, but still binds the instance of the `AudioSource` to the playback of the sounds it started. Calling `AudioSource.Stop()` would effectively stop all the sounds it started, whether by `PlayOneShot` or `Play` for the attached `AudioClip`.

    I think your best shot would be to have a separate `AudioSource` for your one-shots. If you're not spatializing these sounds, you could probably use the same source for all of them.
     
    angeldevelopment likes this.
  4. angeldevelopment

    angeldevelopment

    Joined:
    Sep 28, 2022
    Posts:
    247
    Thanks for the reply and the info! Does PlayOneShot follow the audio source as well? Like if the audio source is moving, and PlayOneShot is called, does the audio get played only from that point, or follow the source, since it binds itself to it?
     
  5. SeventhString

    SeventhString

    Unity Technologies

    Joined:
    Jan 12, 2023
    Posts:
    407
    I imagine it does, but honestly have not tested. It should be fairly simple to find out!
    I would be surprised if it doesn't.
     
    angeldevelopment likes this.