- Home /
I want my trigger to play sound only once!
I just wanted to start of saying that im not so good at scripting. I have this script that makes it so when gameobject, tag "Player" enters the trigger area, sound plays. Well when i enter the area it plays the sound but when i enter the area again the sound plays again and i want it to only be able to play once. Here is the script
var Sound : AudioClip;
function OnTriggerEnter(){
audio.PlayOneShot(Sound);
}
(javascript)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class soundtrigger : MonoBehaviour
{
public AudioClip SoundToPlay;
public float Volume;
AudioSource audio;
public bool alreadyPlayed = false;
void Start()
{
audio = GetComponent<AudioSource>();
}
void OnTriggerEnter()
{
if (!alreadyPlayed)
{
audio.PlayOneShot(SoundToPlay, Volume);
alreadyPlayed = true;
}
}
}
Answer by FLASHDENMARK · Jul 27, 2012 at 08:20 PM
var Sound : AudioClip;
private var hasPlayed = false;
function OnTriggerEnter(){
if(!hasPlayed){
audio.PlayOneShot(Sound);
hasPlayed = true;
}
}
Here you go.
I like the idea to destroy the triggering object - but why would you still need to test and set the hasPlayed variable? If the trigger is gone, then the sound should not be triggered again anyways?
This works really well for an on$$anonymous$$ouseEnter on a texture GUI buttons too. Thanks for posting this code OrangeLightning :)
Answer by IndieScapeGames · Jul 27, 2012 at 08:22 PM
Taking OrangeLightening's example and going a bit further, you could also delete the object you are colliding with.
var Sound : AudioClip;
private var hasPlayed = false;
function OnTriggerEnter(){
if(!hasPlayed){
audio.PlayOneShot(Sound);
hasPlayed = true;
Destroy(GameObject); //untested
}
}
Also, make sure that you have attached an Audio Source to the object, and that your main camera has 1 (one) audio listener.
Thanks for the +1, I really want to get my $$anonymous$$arma up (is it $$anonymous$$arma here like on StackOverflow??) and help Unity newcomers.
The FAQ describes it as $$anonymous$$arma/Reputation.
that would be problematic though, as it stands...
Destroy(gameObject); // lower case
but if you destroy the object, I think the sound may be cut short
you could add
if(!audio.isPlaying())
Destroy(gameObject);
to let the sound play through
Continuing with the idea of the cutting sound:
var Sound : AudioClip;
private var hasPlayed = false;
function OnTriggerEnter(){
if(!hasPlayed){
AudioSource.PlayOneShot(Sound);
hasPlayed = true;
Destroy(gameObject);
}
}
Then an audio source object is created independant of the gale object and should be destroyed when the clip is over after the object is already gone.