How to play audio when gun is fired?

When I fire my gun I want an audio clip to play the gunshot. I’m not sure how to do it though. Here’s my script.

using UnityEngine;
using System.Collections;

public class Shoot : MonoBehaviour {
	
	public Rigidbody bulletPrefab;
	public Transform spawnPoint;
	public int speed;
	public float nextFire = 0.0f;
	public float fireRate = 0.1f;

	// Use this for initialization
	void Start () {
		//nextFire *= Time.deltaTime;
	
	}
	
	// Update is called once per frame
	void Update () {
		
		if(Input.GetKey(KeyCode.Mouse0) && Time.time > nextFire)
		{
			Shot();
		}

	
	}

	void Shot()
	{
		nextFire = Time.time + fireRate;
		Rigidbody bulletInstance;
		bulletInstance = Instantiate(bulletPrefab, spawnPoint.position, bulletPrefab.transform.rotation) as Rigidbody;
		bulletInstance.AddForce(spawnPoint.forward * speed);

	}
}

2 Answers

2

Everything you need is basically in there…

could you write the peice I need in my script, because although you gave me that url, I still don't know what to use.

public AudioClip : gunshotSound; void WhereverYouWantToCallItFrom(){ audio.PlayOneShot(gunshotSound, 1.0); } This should help you out, "1.0" is the volume you want it to play at, this is normalised so 1.0 is full volume, 0.0 is muted.

Thank you for the help. I'll still use this.

It should* work. If it doesn't, post your code here and I'll help you figure it out.

The answer is not wrong. It's quite crude but it works. And though I agree that it's not a good solution, your improvement is only so much better considering you still don't use pooling, the function is static and not thread safe and all the other problems that exist with the solution that are far more important.

begin by adding an audio source component to the gun.
then import the audio file and make sure it doesn’t automatically loop.

and then simply add the audio.Play() function to your code

Thanks for the help!