- Home /
Play audio on keyboard click?
Hi I have a simple script that plays different audio clips on various button or mouse clicks, now I have the code setup to play an audio clip that is assigned in a public variable on left mouse click, but I need it to do that and also play the audio that is assigned to the audio source when I click the up and down arrow keys, I thought I had it figured out, but it keeps giving me the error/errors below. Also Please give me the code in C# thanks.
Error: Assets/AudioTrigger.cs(21,17): error CS0029: Cannot implicitly convert type float' to
bool'
Here's the code I'm using: using UnityEngine; using System.Collections;
[RequireComponent(typeof(AudioSource))] public class AudioTrigger : MonoBehaviour { public AudioClip swing; // Use this for initialization void Start () {
}
// Update is called once per frame
void Update ()
{
if(Input.GetButtonDown("Fire1"))
audio.PlayOneShot(swing);
if(Input.GetAxis("Vertical"))
audio.Play();
}
}
Answer by Landern · Mar 07, 2013 at 02:32 PM
Your problem is with Input.GetAxis which returns a float.
From the documentation:
The value will be in the range -1...1 for keyboard and joystick input. If the axis is setup to be delta mouse movement, the mouse delta is multiplied by the axis sensitivity and the range is not -1...1.
The should look like:
if(Input.GetAxis("Vertical") > 0)
audio.Play();
// or
if(Input.GetAxis("Vertical") < 0)
audio.Play();
Ok That worked, but now it rapidly plays the audio clip so it just sounds like buzzing. What I'm trying to do by the way is have it so when I click the up or down arrows on the keyboard it plays my footsteps sound in the audio source.
You can't oneshot the audio and then loop it?
Or make it so when it plays, have a bool "audioPlaying = true" and only play when it's false. And then have "audioPlaying = false" when the audio stops, or when GetAxis("Vertical") = 0
I am sorry, but I'm new to program$$anonymous$$g is there anyway you could show me what your talking about or something else?
if (!audio.isPlaying)
{
if(Input.GetAxis("Vertical") > 0)
audio.Play();
}
Your answer
Follow this Question
Related Questions
How to create sound on keyboard button? 1 Answer
How to play loop an audio clip on button hold down? 3 Answers
Object won't rotate z axis on second click? 2 Answers
How to emit an audioClip on Collision 0 Answers
help sound on collision when key down 2 Answers