Question by
inaudiblefuzz · Feb 09, 2019 at 02:48 AM ·
c#audioscripting beginnersound
Quick Audio Question - Trying to add sound to gun
I'm trying to add a sound to my gun when firing. I have an error message 'audioclip doesn't contain a definition for play.' Thank you!
public class Gun : MonoBehaviour {
public float damage = 10f; //Damage
public float range = 500f; //Range of bullet
public float fireRate = .50f; //Greater fire rate = less time between shots.
public float impactForce = 30f; //Impact (force)
public ParticleSystem Rail; //Particle System (Muzzle)
public Camera fpsCam; //Camera. Click and drag off of hierarchy
public GameObject impactEffect; //Prefab system for impact
public AudioClip slug; //Gun shot sound
private float nextTimeToFire = 0f; //Instant shot (no lag when pressing down)
void Update()
{
if (Input.GetButtonDown("Fire1") && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
slug.Play();
}
}
void Shoot()
{
Rail.Play(); //Play muzzle / barrel
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
if (hit.rigidbody != null) //Hit RIGIDBODY component
{
hit.rigidbody.AddForce(-hit.normal * impactForce);
}
GameObject impactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impactGO, .25f); // Destroy impact effect
{
}
}
}
} `
Comment
Best Answer
Answer by f03n1x · Feb 09, 2019 at 07:03 AM
You're on the right track, however the clip is just the sound file, what you need is an audio source component, you can add it to the gameobject at the start or as part of the prefab, then if you only need one clip to play do something like the following:
AudioSource audioSource = GetComponent<AudioSource>();
audioSource.clip = slug;
audioSource.Play();
You can also setup the audio source default clip to be that specific clip, and essentially get rid of setting it through code.