I have been looking around some but cant find a good awnser about my problem with gunfire. I have a audio file in my project, left now is the scripting to get it to play when i fire my weapon with GetButtonDown. I have a feeling that it is not a hard thing to do, but i cant get it to work.
public class ShootRifle : MonoBehaviour
public AudioSource shoot;
void Update () {
if (Input.GetButtonDown("Fire1"))
{
shoot.play();
Rigidbody instantiatedProjectile = Instantiate (projectile,
transform.position,
transform.rotation)
as Rigidbody;
instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0,0,Speed));
}
}
I tryd some stuff allready so thats why the shoot.play and audioSource is there.
3 Answers
3
Hi,try using playoneshot
public AudioClip shoot;
void Update(){
if (Input.GetButtonDown("Fire1"))
{
audio.PlayOneShot(shoot);
///yopur other firing code
}
}
You have not attached an audio source to the weapon… Select your weapon and put an audio source on it. You will get it in Components Menu…
After that :
public AudioClip abc; //Drag your audio clip here in unity
void yourFunction(){
--------
if (Input.GetButtonDown("Fire1"))
{
shoot.play();
Rigidbody instantiatedProjectile = Instantiate (projectile,
transform.position,
transform.rotation)
as Rigidbody;
abc.Play();
instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0,0,Speed));
}
}
}
public AudioClip sound1;
public AudioClip sound2;
void function1()
{
audio.clip = sound1;
audio.Play();
}
void function2()
{
audio.clip = sound2;
audio.Play();
}
You need sound source component to be attached to the object with the scrip.
attach an audio component to the object. this.audio.Play() the word shoot doesn't make sense in this context unless you did some kind of audiosource shoot = this.audio;
– sparkzbarcaI got a bit forward now but the audio still wont play, i managed to add the audio to the script now, but i get an error saying there is no "AudioSource" attached to the "Firespawn" game object. WHat did i miss?
– Wingbeatz