- Home /
Sound volume on different colisions
I have a sound and an object to collide with. I want the sound to play (but muted) on awake, but to un-mute on collision.
Tbh, I have no idea how to script it. Can someone help, I tried using unity library and coding it myself, but I get serious compiler errors all of the time.
Answer by Ricardo100 · May 10, 2018 at 12:33 PM
You can create an audio manager and create a reference of the audiosource that changes the volume according to the collision. Or you can just use the functions Stop() and Play()
public AudioSource asource;
void Awake()
{
asource.volume = 0;
}
void OnCollisionEnter(Collision collision)
{
if (collision.tag == "Object") // Tag of the gameobject that contains this collider
audioSource.volume = 1;
}
I didn't tested the script but I guess you can have an idea of how it works.... Some Unity documentation references: AudioSource: https://docs.unity3d.com/ScriptReference/AudioSource.html
Collision: https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html
Be aware of the collision types, if you are using a trigger the callback name changes to OnTriggerEnter instead of OnCollisionEnter.
Thanks! I was already looking at the documentation, for both audio source and collides, but I can't seem to write the hole script on my own. I am really a beginner at this.
I use mute, ins$$anonymous$$d of start/stop, because I have different audio sources (from different collisions) that should play together in harmony. Start/stop will just play them randomly and the mix of them will be chaotic.
There is a more complex way but it will save time on the future, study about Resources.Load() so you can use a single audiosource but load a new audioclip when you need a new clip, or just create prefabs of these sounds and instantiate them and destroy after a few seconds as you need. Good luck with your project ;)
can you help me with the basic script you have just begun on your answer?