- Home /
mute/un-mute
Hi!
I have the following script, which attached to an object with audio source, un-mutes the audio upon collision with FPPlayer.
How should I modify the script to mute the audio after a second collision and mute/un-mute it on every next (like a on/off button upon colliding)?
using UnityEngine;
// make sure the game object you attach it to has an AudioSource on it
[RequireComponent(typeof(AudioSource))]
// create a script that you can attach to a game object
public class SetVolumeOnCollision : MonoBehaviour {
// the volume to set when collided; can be set in the Editor;
// not necessarily needed, but it will make the component more versatile
[SerializeField] private float volumeOnCollision = 1;
// the tag to which it should react; also not essential, but nice to have
// make sure you set the tag of your colliding object if you do use it!
[SerializeField] private string tagToReactTo = "Player";
// the audio source you want to control
private AudioSource audioSource;
// this is called in the first moment, even before sounds start to play
private void Awake () {
// get the audio source to control that is on this game object
audioSource = GetComponent<AudioSource>();
// set volume to 0, muting it; you can also do this in the Editor
audioSource.volume = 0;
// make sure it wil start to play; this as well can be set in the Editor
audioSource.playOnAwake = true;
}
// this function is called on the frame when something collides with this game object
private void OnCollisionEnter (Collision collision) {
// check the tag; remove this if you don't want it
if (collision.collider.CompareTag(tagToReactTo))
// set the desired voluem; just replace it with 1 if you don't want to use desired volume
audioSource.volume = volumeOnCollision;
}
}
Answer by Glurth · May 13, 2018 at 06:22 PM
Add a boolean member variable to the class, which records the current muteState;
bool muteState=false;
Also, add a float to record the originalVolume of the audio source, before you mute it.
float originalVolume;
Now, in OnCollisionEnter, you can Set the volume Based upon this:
if( ! muteState) //if not muted, mute it
{
originalVolume= audioSource.volume ;
audioSource.volume =volumeOnCollision; //muted
}
else //if already muted, UN-mute it
{
audioSource.volume = originalVolume;
}
Then toggle the muteState like so:
muteState= ! muteState;
thank you! can you combine it with the code I already have, I seem to have troubles doing it...
I'm happy to help, but no, I'm not going to do it FOR you.
I don't have coding experience, I can't do it myself in the near future. I'm would not ask for help If I could do it myself for less than 24 hours.
Your answer
Follow this Question
Related Questions
Is there a way to create a random Audiosource loop? 2 Answers
Realistic Sound Effect 0 Answers
Audio Loops? 1 Answer
Audio in WEBGL on IOS devices -1 Answers
PlayOneShot returns false for isPlaying 5 Answers