[Unity 5.5.1f1] [C#]
我刚刚制作了一个重新加载脚本,它应该在开始重新加载时立即播放声音。
该脚本运行完美,但声音在完成重新加载时开始播放。
将行向上移动到当前 if 之外,到 if (currentClip <= 0 || pressedR == true)
下面也不起作用。
有人知道如何在重新加载开始后立即播放声音吗? (最好在 if (totalAmmo > 1)
下,这样当所有储备弹药也耗尽时它不会播放)
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetKey(KeyCode.Mouse0) && counter > DelayTime && reloading == false)
{
Instantiate(Bullet, transform.position, transform.rotation); //Spawning the bullet
currentClip += -1;
counter = 0;
}
if (Input.GetKey(KeyCode.R)) //This will allow the player to use "R" to reload.
{
pressedR = true;
}
//Start of reloading
if (currentClip <= 0 || pressedR == true)
{
reloading = true;
if (totalAmmo > 1)
{
GetComponent<AudioSource>().Play(); // <-- AUDIO AUDIO AUDIO
reloadCounter += Time.deltaTime;
if (reloadCounter > reloadTime)
{
missingAmmo = clipSize - currentClip;
if (totalAmmo >= missingAmmo)
{
totalAmmo += currentClip;
totalAmmo += -clipSize;
currentClip = clipSize;
}
else
{
currentClip += totalAmmo;
totalAmmo = 0;
}
reloading = false;
pressedR = false;
reloadCounter = 0;
//End of reloading
}
}
}
counter += Time.deltaTime;
}
最佳答案
这里发生的事情是在重新加载过程中每一帧都在播放剪辑,它会不断重新启动它直到重新加载完成。因此,直到最后你才能听到完整的剪辑播放,这就是为什么音频似乎只是在重新加载过程之后才播放的原因。
要解决此问题,您应该在重新加载逻辑之外调用 AudioSource.Play()
- 最好是在您第一次触发重新加载开始时调用。但是,您目前有多个进入重新加载过程的入口点 - 当当前剪辑为空时,或者当按下 R 时。我建议将这两个条件移动到相同的 if 条件中,并设置一个标志以在其中一个为真时开始重新加载。此时,您可以调用 AudioSource.Play()
,因此每次重新加载只会触发一次:
void FixedUpdate()
{
if (Input.GetKey(KeyCode.Mouse0) && counter > DelayTime && reloading == false)
{
// ...
}
// Start reloading if not already reloading and either R is pressed or clip is empty
if (!reloading && (Input.GetKey(KeyCode.R) || currentClip <= 0))
{
reloading = true;
GetComponent<AudioSource>().Play();
}
//Start of reloading
if (reloading)
{
if (totalAmmo > 1)
{
reloadCounter += Time.deltaTime;
if (reloadCounter > reloadTime)
{
missingAmmo = clipSize - currentClip;
if (totalAmmo >= missingAmmo)
{
totalAmmo += currentClip;
totalAmmo += -clipSize;
currentClip = clipSize;
}
else
{
currentClip += totalAmmo;
totalAmmo = 0;
}
reloading = false;
reloadCounter = 0;
//End of reloading
}
}
}
counter += Time.deltaTime;
}
请注意,我出于我的目的使用了您的 reloading
标志,因为在此之前它并没有做很多事情。通过这样做,我能够从您的代码中消除 pressedR
,从而降低一些复杂性。
希望对您有所帮助!如果您有任何问题,请告诉我。
关于c# - 音频播放晚于应有的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42100950/