【发布时间】:2017-08-29 20:12:40
【问题描述】:
不知道为什么会发生这种情况,但此代码允许在重新加载后发射 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;
}
【问题讨论】:
-
当您的弹药用完时,您的 Reload() 协程似乎在 Update() 中被多次调用 - 除非设置“isFiring”的任何设置阻止...
-
@ryemoss isFiring 是从另一个脚本设置的,例如 if(Input.GetMouseButtonDown(0)) { playerGun.isFiring = true; } else if (Input.GetMouseButtonUp(0)) { playerGun.isFiring = false; }
-
所以当你发射最后一个子弹时,你会开始重新加载,但是很多帧会过去,在你放开鼠标按钮之前 Reload() 会被多次调用。这可能不是您的问题的原因 - 但应该以任何一种方式解决。你应该确保在启动协程之前你还没有重新加载。
-
将此行修改为。
else if (ammoRemaining == 0 && !isReloading)或者这个:if(isFiring == true && !isReloading) -
不要在
Update()里面调用GetComponent<>(),你正在使用的组件每次都是一样的,而不是public Transform ammoText;做public Text ammoText,你可以拖动相同统一编辑器中的组件,它会为您执行一次 GetComponent 并存储它。
标签: c# unity3d coroutine reloading