- Home /
Answer by Aurelio Provedo · Apr 14, 2011 at 06:40 AM
Add an AudioSource component to the object, and set it to looping in the editor. Then create a script and add it to the object too, after adding this code in the Update method:
if ( Input.GetButtonDown( "Horizontal" ) || Input.GetButtonDown( "Vertical" ) )
audio.Play();
else if ( !Input.GetButton( "Horizontal" ) && !Input.GetButton( "Vertical" ) && audio.isPlaying )
audio.Stop(); // or Pause()
I haven't actually checked it, but it should work. You should get the idea.
Just a small edit. The first condition would look better like this: if ( ( Input.GetButtonDown( "Horizontal" ) || Input.GetButtonDown( "Vertical" ) ) && !audio.isPlaying ) This way the sound will not be played again when more than one key is pressed at a time.
Answer by Nolirneen · Apr 14, 2011 at 06:33 AM
I've never tried putting in audio before, but perhaps you're looking for something like this?
var AudioFile : AudioClip;
function Update() {
if (Input.GetKeyDown ("w"))
{
audio.clip = AudioFile;
audio.Play();
}
else
{
audio.clip = AudioFile;
audio.Pause();
}
}
It should work. =)
Nolirneen, in the script, where would to describe what sound it is? Like how would you tell the script what sound to play?
Answer by cpt_me0w · Jul 25, 2013 at 06:04 PM
Hi, i know this is an old thread, but i still wanted to share. if you want to make the sound fade in and out depending on if the player is mooving or not, i actually made the audioclips volume dependant on the magnitude of the characters movement.
audio.clip = playerWalkSound;
audio.volume = horizontalMovement.magnitude * 0.01;
if(horizontalMovement.magnitude > maxWalkSpeed * playerWalkSoundThreshholdRatio){
if(!playerWalkSoundCreated){
audio.Play();
playerWalkSoundCreated = true;
}
}else{
audio.Stop();
playerWalkSoundCreated = false;
}
i don't know if this is stupid or not, but i wanted to throw it out here :)
Answer by zero84085 · Sep 08, 2012 at 07:14 PM
be sure to check the (is grounded) topics because you dont want to press the jump button and the wasd keys and in the air, hear footsteps Here is: http://docs.unity3d.com/Documentation/ScriptReference/CharacterController-isGrounded.html
Answer by Skyline Studios · Sep 16, 2012 at 10:14 PM
var AudioFile : AudioClip;
function Update() {
if (Input.GetKeyDown ("w"))
{
audio.clip = AudioFile;
audio.Play();
}
else
if (Input.GetKeyUp ("w")) { audio.clip = AudioFile; audio.Pause(); } }
Your answer
![](https://koobas.hobune.stream/wayback/20220613122712im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Sticky keys on all Unity apps 4 Answers
Locomotion System - difference between OnFootLand and OnFootStrike 1 Answer
Rigidbody problem 0 Answers
Footsteps script problem and question 0 Answers