I created a gun script allowing my gun to fire as well as a weapon swap script, but when I swap weapons it plays the noise.
using UnityEngine;
public class WeaponSwap : MonoBehaviour
{
[SerializeField] int selectedWeapon = 0;
// Start is called before the first frame update
void Start()
{
SelectWeapon();
}
// Update is called once per frame
void Update()
{
int previousSelectedWeapon = selectedWeapon;
if (Input.GetAxis("Mouse ScrollWheel") > 0)
{
if (selectedWeapon >= transform.childCount - 1)
selectedWeapon = 0;
else
selectedWeapon++;
}
if (Input.GetAxis("Mouse ScrollWheel") < 0)
{
if (selectedWeapon <= 0)
selectedWeapon = transform.childCount - 1;
else
selectedWeapon--;
}
if (Input.GetKeyDown(KeyCode.Alpha1))
{
selectedWeapon = 0;
}
if (Input.GetKeyDown(KeyCode.Alpha2))
{
selectedWeapon = 1;
}
if (previousSelectedWeapon != selectedWeapon)
{
SelectWeapon();
}
}
void SelectWeapon()
{
int i = 0;
foreach (Transform weapon in transform)
{
if (i == selectedWeapon)
weapon.gameObject.SetActive(true);
else
weapon.gameObject.SetActive(false);
i++;
}
}
}
using UnityEngine;
public class Gun : MonoBehaviour
{
[SerializeField] float damage = 10f;
[SerializeField] float range = 100f;
[SerializeField] float fireRate = 15f;
[SerializeField] float force = 30f;
[SerializeField] AudioClip fireNoise;
[SerializeField] Camera fpsCam;
[SerializeField] ParticleSystem muzzleFlash;
[SerializeField] GameObject impactEffect;
private float nextTimeToFire = 0f;
public AudioSource source { get { return GetComponent<AudioSource>(); } }
private void Start()
{
gameObject.AddComponent<AudioSource>();
source.clip = fireNoise;
}
void Update()
{
if (Input.GetButtonDown("Fire1") && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
PlaySound();
}
}
void Shoot()
{
RaycastHit hit;
muzzleFlash.Play();
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
GameObject impactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impactGO, 2f);
}
}
void PlaySound()
{
source.PlayOneShot(fireNoise);
}
}
I tried removing the PlaySound()
from the update but that didn’t stop it, so I put it back and tried moving the audio clip selection from Start()
to Update()
and that didn’t work either.