Stop Audio clip from playing

I am making a horrorgame and want a sound to play when im passing a trigger. The problem is that it wont keeps being triggered every time I enter the trigger. What i want is to enter the trigger, play the sound, and then it has to never play again. I tried many things like destroying the clip.. but I cant seem to make it work properly.

public class SoundScript : MonoBehaviour 
{    
    public AudioClip Snd_Sound;

    IEnumerator Wait(){
        yield return new WaitForSeconds(20000);
        }

    void OnTriggerEnter(Collider col)
    {               
            audio.enabled = true;
            audio.PlayOneShot(Snd_Sound, 1f);
            StartCoroutine(Wait());
            //??? 
    }   
}

Also it seems that my wait for second doesn't function.

Upvotes: 0

Views: 1880

Answers (2)

LanYi
LanYi

Reputation: 169

Sorry if I misunderstood your question, my English is bad :/ I understood that you need to make the audio source never play again after the first entering, even if the player enters the trigger for the second time

The simplest way is destroy this trigger game object or this script which handles the playing of audio after you entered it. After the audio has finished to play, you can use Destroy() function, like Destroy(gameObject) or Destroy(this)

You can also declare a variable which handles the playing of this audio, such as:

bool playsound; //assign the value of **true** in Inspector
void OnTriggerEnter(Collider col)
{   
    if(playsound){
        audio.enabled = true;
        audio.PlayOneShot(Snd_Sound, 1f);
        playsound = false;
    }       
}  

Upvotes: 1

Paul-Jason
Paul-Jason

Reputation: 737

I would create a child object that holds the sound bite and expose a public method to play the sound. Then within your SoundScript object, create a variable storing the child objects script. When OnTriggerEnter is triggered, check if the variable is not null. If not, then call the public method in the child object and set the variable to null. Have the child script destroy itself after the soundbite has finished playing. With the child game object removed from the scene, it cannot be played again.

Upvotes: 0

Related Questions