Playing sound only once?

I want to make that when i look at object at certain distance it plays a loud boom. And when i look elsewhere it resets the sound so that when i look again it plays again. This what i’ve put together but it doesnt work.

if(dist < 10){
    					
    	if(!audio.isPlaying){
    		audio.PlayOneShot(Boom);
        }

Instead it plays the sound once ok. The other audio in the sctipt wont play until i go closer than 10. Whats wrong? Im kind of new to the audio in unity.

isPlaying only works when the sound was started with Play() - sounds started with PlayOneShot don’t set isPlaying. You could use Play like this:

if (dist < 10){
  if (!audio.isPlaying){
    audio.clip = Boom;
    audio.Play();
  }
  ...

But this code will do nothing if another clip is already playing in this same AudioSource. If you have other sounds that may be playing, a better solution is to create a private PlayOneShot version:

JS version:

private var clipEnd: float; // declare this outside any function

function MyPlayOneShot(sound: AudioClip){
  if (Time.time > clipEnd){ // if previous clip not playing anymore...
    audio.PlayOneShot(sound); // play the new one...
    clipEnd = Time.time + sound.length; // and calculate its end time
  }
}

C# version:

private float clipEnd; // declare this outside any function

void MyPlayOneShot(AudioClip sound){
  if (Time.time > clipEnd){ // if previous clip not playing anymore...
    audio.PlayOneShot(sound); // play the new one...
    clipEnd = Time.time + sound.length; // and calculate its end time
  }
}

Then call it as a regular PlayOneShot:

if (dist < 10){
  MyPlayOneShot(Boom);
  ...