ARTICLE AD BOX
I'm trying to create a First Person Shooter (FPS) game on Unity. I'm currently facing animation + sound effect (sfx) problems as they are not getting synced. The shooting sound effect is getting played in between animations playing.
Below is my main Gun Script and Scriptable Object it is using:
using System.Collections; using UnityEngine; public class Gun : MonoBehaviour { public GunsSO GunData; public Animator gun_animator; int current_ammo; bool isReloading = false; float nextTimeToFire = 0f; public AudioSource shoot_sfx; public AudioSource reload_sfx; private void Start() { current_ammo = GunData.mag_size; } private void Update() { // Shoot if (Input.GetMouseButtonDown(0)) { TryShoot(); } // Reload if (Input.GetKeyDown(KeyCode.R)) { TryReload(); } } void TryReload() { if (!isReloading && current_ammo < GunData.mag_size) { StartCoroutine(Reload()); } } IEnumerator Reload() { isReloading = true; // Optional: play reload animation if (gun_animator != null) { gun_animator.SetTrigger("Reload"); } reload_sfx.Play(); yield return new WaitForSeconds(GunData.reloading_time); current_ammo = GunData.mag_size; isReloading = false; } void TryShoot() { if (isReloading) return; if (current_ammo <= 0) { TryReload(); return; } if (Time.time >= nextTimeToFire) { nextTimeToFire = Time.time + GunData.shoot_time; HandleShoot(); } } void HandleShoot() { current_ammo--; // Play shoot animation using trigger if (gun_animator != null) { gun_animator.SetTrigger("Shoot"); } if (!shoot_sfx.isPlaying) { shoot_sfx.Play(); } } } using UnityEngine; [CreateAssetMenu(fileName = "GunsSO", menuName = "Scriptable Objects/GunsSO")] public class GunsSO : ScriptableObject { public string Name; public float shoot_time; public float reloading_time; public int mag_size; public AudioSource shoot_sfx; }How to fix this? Should the shoot sound effect have the same length as the shooting animation?
Most importantly, how do professionals handle this situation?
New contributor
Maan is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
1
Explore related questions
See similar questions with these tags.
