- Home /
Muting An Overlapping Audio Clip?
Hi Everyone!
I'm hoping that someone here can help me with a problem that I'm having. I'm trying to get back into coding in Unity and I'm having an issue with the script below. This script is being used to open and close a door and currently what is happening is when the door is closing; both the "Open Sound" and "Close Sound" is playing at the same time. Does anyone know how I can make it so that when the door is closing, only the close sound is playing?
// Smothly open a door
var smooth = 2.0;
var DoorOpenAngle = 90.0;
var open : boolean = false;
var doorOpenSound : AudioClip;
var doorCloseSound : AudioClip;
@script RequireComponent(AudioSource);
private var enter : boolean;
private var defaultRot : Vector3;
private var openRot : Vector3;
function Start()
{
defaultRot = transform.eulerAngles;
openRot = new Vector3 (defaultRot.x, defaultRot.y + DoorOpenAngle, defaultRot.z);
}
//Main function
function Update ()
{
if(open)
{
//Open door
transform.eulerAngles = Vector3.Slerp(transform.eulerAngles, openRot, Time.deltaTime * smooth);
}
else
{
//Close door
transform.eulerAngles = Vector3.Slerp(transform.eulerAngles, defaultRot, Time.deltaTime * smooth);
}
if(Input.GetKeyDown("f") && enter)
{
open = !open;
audio.PlayOneShot(doorOpenSound);
}
if(Input.GetKeyDown("f") && enter && !open)
{
audio.PlayOneShot(doorCloseSound);
}
}
function OnGUI()
{
if(!open && enter)
{
GUI.Label(new Rect(Screen.width/2 - 75, Screen.height - 100, 150, 30), "Press 'F' to open the door");
}
if (open && enter)
{
GUI.Label(new Rect(Screen.width/2 - 75, Screen.height - 100, 150, 30), "Press 'F' to close the door");
}
}
//Activate the Main function when player is near the door
function OnTriggerEnter (other : Collider)
{
if (other.gameObject.tag == "Player")
{
enter = true;
}
}
//Deactivate the Main function when player is go away from door
function OnTriggerExit (other : Collider)
{
if (other.gameObject.tag == "Player")
{
enter = false;
}
}
Answer by Baste · Sep 17, 2014 at 12:41 PM
You've forgotten to check if the door is closed when you play the opening sound! Here's the problem:
if(Input.GetKeyDown("f") && enter)
{
open = !open;
audio.PlayOneShot(doorOpenSound); // <== PROBLEM LINE
}
The line marked above will be called both when the door is open and closed.
The way to fix this is to replace this:
if(Input.GetKeyDown("f") && enter)
{
open = !open;
audio.PlayOneShot(doorOpenSound);
}
if(Input.GetKeyDown("f") && enter && !open)
{
audio.PlayOneShot(doorCloseSound);
}
with this:
if(Input.GetKeyDown("f") && enter)
{
if(closed)
audio.PlayOneShot(doorOpenSound);
else
audio.PlayOneShot(doorCloseSound);
open = !open;
}
Thanks Baste! I had to add another variable to get it to work but the code you supplied aided the solution. I'm more of an artist than a coder but I have some knowledge of coding =P
Thanks again!