I am making a game in unity and whenever I walk into a box trigger I want it to play audio from another objects audio source in the scene. How would I do that.
CodePudding user response:
Maybe something like this is what you need ?
Remember this code must go on the object that has the box trigger, and don't forget to set the correct parameters for on trigger to work (https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html)
private void OnTriggerEnter(Collider other)
{
if(other.name == "WalkingObject") //can also use other.tag
{
GameObject.Find("ObjectWithAudioSource").GetComponent<AudioSource>();
}
}
you can also store that Audio source in a variable like so
AudioSource audioSource;
private void OnTriggerEnter(Collider other)
{
if(other.name == "YourObject")
{
audioSource = GameObject.Find("ObjectWithAudioSource").GetComponent<AudioSource>();
}
}
Than if you need you can add .Play or whatever you need after it
more on audio source https://docs.unity3d.com/ScriptReference/AudioSource.html
Also if you use OnTriggerEnter(Collider other) you may also need OnTriggerExit(Collider other), Which would stop the trigger executing (if you need it) (https://docs.unity3d.com/ScriptReference/Collider.OnTriggerExit.html)
