- Home /
(help) Door sound
So, when I press Q the door opens and the audio plays at the same time but when I close the door, the sound doesn't play until the door is closed. I want it to play at the same time as the door closes. Here is the script I used:
var IsOpen : boolean = false;
var CanOpen : boolean = false;
var Volume : float = 0.5;
function Start () {
audio.volume = Volume;
}
function Update () {
if(Input.GetKeyUp(KeyCode.Q) && !IsOpen && CanOpen)
{
Opening();
IsOpen = true;
audio.Play();
}
else if(Input.GetKeyUp(KeyCode.Q) && IsOpen && CanOpen)
{
Closing();
IsOpen = false;
}
}
function Opening()
{
for (var i = 0; i < 100; i++)
{
transform.Translate(-0.017,0,0);
yield WaitForSeconds(0.01);
}
}
function Closing()
{
for (var i = 0; i < 100; i++)
{
transform.Translate(0.017,0,0);
yield WaitForSeconds(0.01);
audio.Play();
}
}
function OnTriggerEnter (other : Collider)
{
if(other.gameObject.tag == "Player")
{
CanOpen = true;
}
}
function OnTriggerExit (other : Collider)
{
if(other.gameObject.tag == "Player")
{
CanOpen = false;
}
}
@script RequireComponent(AudioSource)
Comment
Best Answer
Answer by FLASHDENMARK · Apr 27, 2014 at 07:50 PM
You placed your audio.Play() call inside the for loop when closing the door.
var IsOpen : boolean = false;
var CanOpen : boolean = false;
var Volume : float = 0.5;
function Start () {
audio.volume = Volume;
}
function Update () {
if(Input.GetKeyUp(KeyCode.Q) && !IsOpen && CanOpen)
{
Opening();
IsOpen = true;
audio.Play();
}
else if(Input.GetKeyUp(KeyCode.Q) && IsOpen && CanOpen)
{
Closing();
IsOpen = false;
audio.Play(); //Added this
}
}
function Opening () {
for (var i = 0; i < 100; i++)
{
transform.Translate(-0.017,0,0);
yield WaitForSeconds(0.01);
}
}
function Closing () {
for (var i = 0; i < 100; i++)
{
transform.Translate(0.017,0,0);
yield WaitForSeconds(0.01);
//audio.Play(); And removed this
}
}
function OnTriggerEnter (other : Collider) {
if(other.gameObject.tag == "Player")
{
CanOpen = true;
}
}
function OnTriggerExit (other : Collider) {
if(other.gameObject.tag == "Player")
{
CanOpen = false;
}
}
@script RequireComponent(AudioSource)
Also a word of advice. Never name variable names with capital starting letters. Like:
CanOpen is generally not good practice.
canOpen is generally better and is a capitalization style called camel case.
It is of course a matter of preference.
Thanks, it worked. And thanks also for the advice. I am new to Unity and scripting.