Wanting audio to pause on trigger enter
I'm very new to Unity so the fix to my issue is probably very straightforward.
I have two scripts, both linked to in-game objects which are used as trigger areas. On my first game object/script, I have an audio source. I want to make it so that when the player enters the second trigger area it stops the audio source from the first one, or pauses it. I don't want to completely get rid of it on trigger enter as it is used multiple time throughout the game. Just stop it so I can start it again later. (I already have some code in these (Not related to the issue))
Object/Script one:
{
public AudioClip BuildUp;
public float timeInterval = 1;
public float counternoise;
void Start()
{
counternoise = 0;
GetComponent<AudioSource>().playOnAwake = false;
GetComponent<AudioSource>().clip = BuildUp;
}
//Plays the sound whenever in trigger area
public void OnTriggerEnter(Collider collider)
{
counternoise = 0;
}
public void OnTriggerStay(Collider collider)
{
counternoise += Time.deltaTime;
if (counternoise > timeInterval)
{
//Die
GetComponent<AudioSource>().Play();
counternoise = -100;
}
}
And the second one (one which stops audio from first on entry)
{
public GameObject DeathArea;
public void OnTriggerEnter(Collider collider)
{
DeathArea.GetComponent<EnterDarknessScript>().counternoise = 0;
}
public void OnTriggerStay(Collider collider)
{
DeathArea.GetComponent<EnterDarknessScript> ().counternoise = 0;
}
}
Thanks a bunch for any help
Answer by Lukas-Wendt · Apr 18, 2018 at 04:07 PM
If the first script is EnterDarknessScript (you should paste the class name with the code so it is easier for us to talk about), you could create a method in EnterDarknessScript called StopAudio. This method could simply do:
public void StopAudio()
{
GetComponent<AudioSource>().Stop();
}
Then you could call this method from your second script like so:
public void OnTriggerEnter(Collider collider)
{
DeathArea.GetComponent<EnterDarknessScript>().StopAudio();
}
You should maybe save a reference to the AudioSource, so you don't need to call GetComponent all the time.
If you want to pause the audio, you can just use the Pause method on the AudioSource.
You can see all the available methods on AudioSources in the documentation here: https://docs.unity3d.com/ScriptReference/AudioSource.html
Your answer
Follow this Question
Related Questions
Audio play when enter trigger 1 Answer
Trying to make a splitscreen game, having issues with the AudioSource and distance between objects. 0 Answers
Stop AudioSource on Trigger!!! 1 Answer
How to use a key as trigger? 2 Answers
Dialogue Problem 0 Answers