Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Resolved How might I trigger an audio oneshot when y position is <0 to play just once?

Discussion in 'Audio & Video' started by CaliDave, Jan 23, 2023.

  1. CaliDave

    CaliDave

    Joined:
    Jan 6, 2023
    Posts:
    2
    Expectation - When a ball rolls off the floor I want to trigger an audio oneshot to play a "falling" sound.
    Problem - With this code the one shot plays many instances of the falling sound. I believe this is because the update continues to see this position as being < 0 and plays multiple instances of the audio file as long as y position is < 0.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Ball : MonoBehaviour
    4. {
    5.     public AudioClip ballFall;
    6.     private AudioSource audioSource;
    7.  
    8.     void Start()
    9.     {
    10.         audioSource = GetComponent<AudioSource>();
    11.     }
    12.  
    13.     void Update()
    14.     {
    15.         if (transform.position.y < 0)
    16.         {
    17.             audioSource.PlayOneShot(ballFall);
    18.         }
    19.     }
    20. }
    ---
    Does anyone have suggestions on how might I rewrite the code so the audio will play only once when the threshold is crossed and not again? Thanks!
     
  2. CaliDave

    CaliDave

    Joined:
    Jan 6, 2023
    Posts:
    2
    This is working using a bool to tell if the clip was played resulting in a single play of the audio clip:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Ball : MonoBehaviour
    4. {
    5.     public AudioClip ballFall;
    6.     private AudioSource audioSource;
    7.     private bool clipPlayed = false;
    8.     private float fallDelay = 0;
    9.  
    10.     void Start()
    11.     {
    12.         audioSource = GetComponent<AudioSource>();
    13.     }
    14.  
    15.     void Update()
    16.     {
    17.         if (transform.position.y < fallDelay && !clipPlayed)
    18.         {
    19.             audioSource.PlayOneShot(ballFall);
    20.             clipPlayed = true;
    21.         }
    22.     }
    23. }