Unity动画和音效不同步
我正在Unity上尝试制作一个第一人称射击游戏(FPS)。 我目前遇到动画与音效(SFX)不同步的问题。 射击音效在动画播放的中间被触发。
下面是我的主枪械脚本以及它所使用的Scriptable Object:
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;
}
如何解决? 射击音效的时长应该与射击动画一致吗?
最重要的是,专业人士通常如何处理这种情况?
解决方案
看起来你的代码没有问题,因为声音是在你扣减弹药并在动画控制器上设置触发条件的同一帧播放的。
我的猜测是,可能是以下情况之一:
- 你的音效在前几秒有延迟。
- 你在上一发尚未结束时就试图播放声音。
- 你的动画实质上不同步,当你为动画控制器设置触发器时,转场可能需要一些时间,导致同步问题。
- 你的音频剪辑导入设置被设为Streaming,这可能导致一些延迟,因为音频需要从存储中读取并解码。
我的建议是在射击前记录日志,看看指令是否在你预期的时间执行,并使用 PlayOneShot,这样可以让你实现多个重叠的射击声音。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。