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.
using UnityEngine;
public class Ball : MonoBehaviour
{
public AudioClip ballFall;
private AudioSource audioSource;
void Start()
{
audioSource = GetComponent<AudioSource>();
}
void Update()
{
if (transform.position.y < 0)
{
audioSource.PlayOneShot(ballFall);
}
}
}
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!