Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. 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. }