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);
}
}
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.
– FPSworriorpublic 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.
– Matthew_ScottThank you for the help. I'll still use this.
– FPSworriorIt should* work. If it doesn't, post your code here and I'll help you figure it out.
– Matthew_ScottThe 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.
– YesNoKonrad