- Home /
How to create a trigger stopping audio in Unity
I am totally new to Unity, so please be forgiving.
I have created a cube in a doorway with "is trigger" checked in the box collider section so an event activates when the player walks through it. I'm trying to get a separate audio source to stop playing when the player walks through the door, but I am very confused by the coding. My understanding is that I must: reference the audio object so the code knows it exists > code that on trigger entry the event happens > code event. Below is my attempt at that.
public class Class : MonoBehaviour { public GameObject AudioSource; void Start() { AudioSource = GameObject.Find("Audio Source"); }
void OnTriggerEnter(Collider other)
{
AudioSource audio = GetComponent<AudioSource>();
audio.Stop();
}
}
Is this even remotely correct?
Answer by Captain_Pineapple · May 08, 2018 at 08:06 AM
Hey there and welcome to unity :)
to start with you probably want to watch some tutorials about the basic functionalitys of unity. I can recommend the native unity tutorials found here.
Anyway: For your current problem you want to stick with the code here:
public class Class : MonoBehaviour {
//Creates a "GameObject" -Type reference:
public GameObject AudioObject;
void Start()
{
//Finds !one! Gameobject named "Audio Source"
AudioObject = GameObject.Find("Audio Source");
//check if we actually found the audiosource object:
if (AudioSource == null) {
Debug.Log ("We did not find the AudioSource");
}
}
void OnTriggerEnter(Collider other)
{
//get the component of the audiosource GameObject
AudioSource audio = AudioObject.GetComponent<AudioSource>();
//check if it really exists:
if (audio != null) {
audio.Stop ();
} else {
Debug.Log ("there is not audioSource on this object");
}
}
}
For reference: I changed the Gameobjects Name to "AudioObject" since you DON'T want to name variable names after Class names. You might get in trouble since the compiler might not know if you mean a Variable or Class type at some point. When you want to access the audiosource you have to call YourObjectsName.GetComponent<ClassNameHere>()
on the object that you actually want to access - so in your case AudioObject.GetComponent<AudioSource>();
Note that you have to check that your "doors" collider has to have the "isTrigger" box checkes as well as the/one collider of your player object. In addition to that one of these objects need a omponent of the Type Rigidbody attached. Otherwise the OnTriggerFunction will never get called.
I hope this helps. In case something i wrote was unclear feel free to ask.
EDIT: You also DON'T want to call your Class "Class". Call it something that actually describes what the class is for. (e.g. "doorAudioStopper")
Thank-you very much, I've managed to get it working now.