- Home /
Question by
RicardoAntezana · Apr 08, 2016 at 07:34 PM ·
audioaudiosourceaudioclipaudio.playoneshotaudio.play
Looping an audio while holding "shift key"
Hey guys, I have a breathing sound effect I have for when my character is sprinting but I struggle to get it to play. Any help please?
if(Input.GetKey(KeyCode.LeftShift))
{
if(energy > 0)
{
moveSpeed = sprintSpeed;
energy -= Time.deltaTime * energySpeed;
GetComponent.<AudioSource>().PlayOneShot(RunningSound);
}
else if(energy < 0)
{
energy = 0;
moveSpeed = 5.0;
}
}
Comment
Best Answer
Answer by phxvyper · Apr 08, 2016 at 07:44 PM
Enable looping with AudioSource.loop. Play when shift is held, but down repeat Play() over and over. Stop() when shift is up.
AudioSource Audio;
void Start()
{
Audio = GetComponent<AudioSource>();
Audio.loop = true;
}
void Update()
{
if (Input.GetKey(KeyCode.LeftShift))
{
if (energy > 0)
{
moveSpeed = sprintSpeed;
energy -= Time.deltaTime * energySpeed;
// Ensure that Play() isnt called over and over again.
// Similer to if (Input.GetKeyDown(KeyCode.LeftShift)) in that it'll only call once after LeftShift is down.
if (!Audio.IsPlaying)
{
Audio.Play();
}
}
else if (energy < 0)
{
energy = 0;
moveSpeed = 5.0;
}
}
else if (Input.GetKeyUp(KeyCode.LeftShift))
{
if (Audio.IsPlaying)
{
Audio.Stop();
}
}
}
Its the same thing, except the function declarations are:
function Start()
{
}
function Update()
{
}
and the AudioSource declaration is:
var Audio : AudioSource;
Your answer
Follow this Question
Related Questions
AudioSource.clip.time won't work? 2 Answers
Audiosource.Play() not working 0 Answers
2nd Audio Clip Not Playing 0 Answers
Breathing volume increases as player gets more tired 0 Answers
Assign a clip to an AudioSource when it finishes playing. 1 Answer