[Unity 5.5.1f1] [C#]
我刚刚制作了一个重新加载脚本,它应该在重新开始加载时发出声音。
该脚本运行正常,但声音在完成DONE重新加载时开始播放。
如果在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;
}
之下,以便在所有预备弹药也耗尽时不会发挥作用)
const state = {
cities: [],
selectedCity: {}
}
答案 0 :(得分:3)
这里发生的事情是在重新加载过程中每个帧都播放剪辑,这会一直重新启动它直到重新加载完成。结果,直到最后才能听到剪辑完整播放,这就是为什么音频只在重新加载过程之后播放。
要解决此问题,您应该在重新加载逻辑之外调用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
,节省了一些复杂性。
希望这有帮助!如果您有任何问题,请告诉我。