How to add sound to gun shot script

So I got this code, that I’m using to make my gun shot in Unity.

var projectile : Rigidbody;
var speed = 20;
function Update()
{
if( Input.GetButtonDown( “Fire1” ) )
{
var instantiatedProjectile : Rigidbody = Instantiate(
projectile, transform.position, transform.rotation );

instantiatedProjectile.velocity =
transform.TransformDirection( Vector3( 0, 0, speed ) );

Physics.IgnoreCollision( instantiatedProjectile. collider,
transform.root.collider );

}
}

Could some one tell me how to update my code so, that everytime left mouse button “Fire1” is pressed, then the sound would be played. I’m not familiar with java scripts.

  • Sajamon Tuzkin
    Ps. Thnx!

I put your question into the Search box above and got this:

http://search.unity3d.com/uss1/?q=How+to+add+sound+to+gun+shot+script&type_of_search=answers

public AudioClip teleportSound; // Add a AudioClip reference

audio.PlayOneShot(teleportSound); // Play the AudioClip

http://answers.unity3d.com/questions/278058/how-to-add-a-sound-to-this-script.html

var projectile : Rigidbody;
var speed = 20;
function Update()
{
if( Input.GetButtonDown( “Fire1” ) ) {

audio.Play();

var instantiatedProjectile : Rigidbody = Instantiate(
projectile, transform.position, transform.rotation );

instantiatedProjectile.velocity =
transform.TransformDirection( Vector3( 0, 0, speed ) );

Physics.IgnoreCollision( instantiatedProjectile. collider,
transform.root.collider );

}
}

Added that “audo.Play();” and shooting sound works nicely now.

if (Input.GetButtonDown(“Fire1”)
{
GetComponent().Play()
}

Make sure to add an audio source to your gameObject.

This script usually works for me :slight_smile: