- Home /
play audio for few seconds on key hit
Hello all. Not much of a coder but I'm trying to have a short audio clip play whenever the player presses spacebar.
Right now the player is able to jump by pressing spacebar and if they hold it down they continue to rise for about three seconds before they begin falling. I would like the audioclip to play for as long as they are rising, but currently it plays the entire audio file (about 27 seconds long). I understand that my current code doesn't tell it to stop, but I'm having a hard time figuring out how to play the audio, wait for three seconds, then stop and reset the audio.
my spacethrusters script (C#) is attached to my fps controller along with the audiosource component.
Any help at all would be great, here's the current code I have:
using UnityEngine; using System.Collections;
public class spacethrusters : MonoBehaviour {
//Update is called once per frame
void Update () {
if (Input.GetKeyDown("space"))
audio.Play ();
}
}
Thanks again.
Answer by Zamaroth · Oct 27, 2013 at 10:50 AM
I suppose you have a variable, used to determine if the player is falling or not. If this variable is called falling, the code to stop the audioclip looks like this:
if(Input.GetKeyUp("space") || (Input.GetKey("space") && falling == true && !audio.isPlaying))
{
audio.Stop();
}
First statement Input.GetKeyUp("space") is used to stop the audioclip when player stops holding the spacebar.
Second statement Input.GetKey("space") && falling == true stops the audioclip when player begin falling, but still holds the spacebar.
!audio.isPlaying is there to ensure that the function won`t be called if the audioclip has been already stopped.
That looks perfect. How would I go about creating the 'falling' variable? I looked into some raycasting options but I got a bunch of errors. Sorry for my inexperience.
Right now the player is able to jump by pressing spacebar and if they hold it down they continue to rise for about three seconds before they begin falling.
Simply create a boolean variable named falling
var falling : boolean;
and set it to true after those 3 seconds.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
someone is there? 1 Answer
Gun Audio reverbs off of Terrian- sounds horrible- What can I do? 0 Answers
Every few seconds, play an audio clip 3 Answers
Vehicle help 1 Answer