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;
}
}