- Home /
Audio Trigger Enter Exit
Having an issue where I want an audio track to play when the player enters the collision area and end when the player leaves. I can't get either function to work and this is as far as I have gotten with the research I have done.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class source : MonoBehaviour {
public AudioClip winner;
AudioSource audioSource;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
audioSource.PlayOneShot(winner);
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player"))
{
audioSource.Stop;
}
}
}
This should work. Are you sure that both functions are playing? Are they even triggered? Did you make sure the player also has a collider?
Also, did you try just 3D sound with rolloff 0 at the distance you want it to stop?
I added a Debug.Log to test if the triggers worked and they don't. Also I've tried out the 3D sound, and it works but sort of does what I want to do. I have background music already, so if it could stop as I entered the 3D sound radius that would be ideal as well, but as of right now both tracks play when I enter.
Do all your triggering objects have a collider?
Answer by Chimer0s · Apr 08, 2018 at 10:41 PM
You may need to declare the winner clip for this to work as you've written it. Although if you're trying to play a looping audio source, there's no need to even go that far. You could simply use:
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player")
{
if (!audioSource.isPlaying)
audioSource.Play();
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player")
audioSource.Stop();
}
Awfully sorry for the late reply, but I tried this and it did end up working. Thank you!