- Home /
OnTriggerExit stop audio
I have a simple code, it's fundamentally a trigger that plays an audio and an animation when the player walks in and stops the audio when the player walks out. I have many of the triggers in the scene working under this code. I was able to make it work when the player walks in, but not when he walks out, as the audio keeps playing even when the player exits the trigger. I have already tried audio.Stop(); but wouldn't work..
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PleaseWork1 : MonoBehaviour
{
public Animator anim;
public AudioClip sound;
void Start()
{
anim.enabled = false;
}
void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == ("Player"))
{
anim.enabled = true;
AudioSource.PlayClipAtPoint(sound, transform.position);
}
}
void OnTriggerExit(Collider col)
{
if (col.gameObject.tag == ("Player"))
{
//this is where I have no idea what to do
}
}
}
Answer by pako · Jan 31, 2019 at 11:30 AM
I haven't tested this, but I suspect the problem is that you don't have a reference to a specific instance of an AudioSource
, so you can't stop it. PlayClipAtPoint()
is a static method, so you can call it without having a specific instance of an AudioSource
: PlayClipAtPoint
However, to stop the sound with AudioSource.Stop
you need a reference to a specific instance of an AudioSource
as detailed in this example.
Let me know if you need any clarifications on the aforementioned example.
It works!
This is the code now
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PleaseWork1 : $$anonymous$$onoBehaviour
{
public Animator anim;
public AudioClip sound;
AudioSource m_$$anonymous$$yAudioSource;
void Start()
{
anim.enabled = false;
m_$$anonymous$$yAudioSource = GetComponent<AudioSource>();
}
void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == ("Player"))
{
anim.enabled = true;
m_$$anonymous$$yAudioSource.Play();
}
}
void OnTriggerExit(Collider col)
{
if (col.gameObject.tag == ("Player"))
{
m_$$anonymous$$yAudioSource.Stop();
}
}
}