不知道爲什麼會發生這種情況,但是此代碼允許在重新加載後觸發超過3顆子彈。我試圖找出原因。我想這可能是檢查這個問題之間的時間,但我可能是錯的。更多子彈產卵超出允許範圍
任何幫助,將不勝感激。
public bool isFiring;
public bool isReloading = false;
public BulletController bullet; // Reference another script
public float bulletSpeed; // bullet speed
public float timeBetweenShots; // time between shots can be fired
private float shotCounter;
public Transform firePoint;
public static int ammoRemaining = 3;
public static int maxAmmo = 3;
public Transform ammoText;
// Use this for initialization
void Awake() {
isReloading = false;
ammoRemaining = maxAmmo;
}
// Update is called once per frame
void Update() {
if(isFiring == true)
{
shotCounter -= Time.deltaTime;
if(shotCounter <= 0 && ammoRemaining > 0 && isReloading == false)
{
shotCounter = timeBetweenShots;
BulletController newBullet = Instantiate(bullet, firePoint.position, firePoint.rotation) as BulletController; // creates a new instance of the bullet
newBullet.speed = bulletSpeed;
ammoRemaining -= 1;
ammoText.GetComponent<Text>().text = "Ammo:" + ammoRemaining;
}
}
else if (ammoRemaining == 0)
{
StartCoroutine(Reload());
}
else
{
shotCounter = 0;
}
}
public IEnumerator Reload()
{
isReloading = true;
ammoText.GetComponent<Text>().text = "REL...";
yield return new WaitForSeconds(2);
ammoRemaining = maxAmmo;
isReloading = false;
ammoText.GetComponent<Text>().text = "Ammo:" + ammoRemaining;
}
它看起來像你的刷新()協同程序是當你用完彈藥時會在Update()中多次調用 - 除非任何set「isFiring」阻止了這一點... – ryeMoss
@ryemoss isFiring從另一個腳本設置如此 if(Input.GetMouseButtonDown(0)) {player} {playerGun.isFiring = true; } else if(Input.GetMouseButtonUp(0)) playerGun.isFiring = false; } – Robertgold
因此,當您觸發最後一顆子彈時,您將開始重新加載,但在放開鼠標按鈕之前,很多幀都會通過並重新加載()將被多次調用。這可能不是你的問題的原因 - 但應該以任何方式解決。你應該確保在啓動協程之前你還沒有重新加載。 – ryeMoss