- Home /
help sound on collision when key down
hi Im brand new to scripting (you can probably tell by my attempt). i was trying to make a script where my player enters a collider and when they press a key it plays a sound. here is my attempt
var soundFile:AudioClip;
if function OnTriggerEnter(trigger:Collider) {
if((trigger.collider.tag=="Player")Input.GetKeyDown("f")=true) {
audio.clip = soundFile;
audio.Play();
}
}
any amendments would be great
thanks
Answer by HarshadK · Sep 29, 2014 at 10:01 AM
Attach an AudioSource Component to your game object to which this script is attached and assign your sound file to the Audio Clip from the inspector.
Also your code will become:
function OnTriggerStay(trigger : Collider) {
if((trigger.gameObject.tag == "Player") && Input.GetKeyDown(KeyCode.F)) {
audio.Play();
}
}
Here you might want to use OnTriggerStay since you want to check for key press to play the audio source for as long as the player is inside the trigger.
all i had to do was a little tweak to the script thanks man
Answer by bubzy · Sep 29, 2014 at 10:00 AM
I would do this :
var collidedWithPlayer :bool = false;
if function OnTriggerEnter(trigger:Collider)
{
if((trigger.collider.tag=="Player")
{
collidedWithPlayer = true;
}
}
function Update() //I use c# so I guess java uses this method for update
{
if(collidedWithPlayer && Input.GetKeyDown(KeyCode.F))
{
audio.clip = soundFile;
audio.Play();
collidedWithPlayer =false;
}
}
however, this will be a little odd, as the key can be pressed at any time to play the sound after the collision happens, its probably best to just have the sound play on collision, or to set a variable true as I did when the f key is pressed and then play the sound on collision in the collision function.