- Home /
Question by
willpark2000 · Sep 09, 2019 at 10:05 PM ·
audiotriggerunity 2d
Can't stop audio source after going away from trigger
So I added a trigger onto a game object, and I want an audio clip to play when the player touches the trigger, and when it is away, I want the audio clip to stop playing. Right now the audio clip plays when I enter the trigger, but once I get out it doesn't stop playing. I thought about another way of doing this, by calculating the distance between the game object and the player. And if the distance between the two get to a certain point then audio clip will play. And once it is out of that distance the audio clip will stop playing. Any ideas?
Here's the current code:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class firstRadarTrigger : MonoBehaviour { AudioSource firstRadar;
private void Start()
{
firstRadar = GetComponent<AudioSource>();
}
// Start is called before the first frame update
void OnTriggerEnter2D(Collider2D collider)
{
if (collider.gameObject.tag == "Player")
{
firstRadar.Play();
}
else
{
firstRadar.Pause();
}
//if (collider.CompareTag("Player"))
{
//firstRadar.Play();
}
//else
{
//firstRadar.Stop();
}
}
// Update is called once per frame
void Update()
{
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612211933im_/https://answers.unity.com/themes/thub/images/avi.jpg)