Question by
Robertgold · Aug 29, 2017 at 10:26 AM ·
c#loopwaitforsecondsreloading
Automatic reloading issues
Hi there, am trying to create automatic reloading when ammo hits 0 or after x seconds of no shots happening. Not sure why the function won't fire currently. Any help please?
Much thanks.
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;
Destroy(newBullet, 5);
}
else if (ammoRemaining >= 0)
{
Reload();
}
}
else
{
shotCounter = 0;
Reload();
}
}
public IEnumerator Reload()
{
isReloading = true;
Debug.Log("AM here...");
yield return new WaitForSeconds(2);
Debug.Log("AM here 2...");
while (ammoRemaining <= maxAmmo)
{
ammoRemaining += 1;
ammoText.GetComponent<Text>().text = "Ammo:" + ammoRemaining;
}
isReloading = false;
}
}
Comment
Best Answer
Answer by Robertgold · Aug 29, 2017 at 11:09 AM
Solved had missed StartCoroutine() around Reload() which caused it not to fire....
Your answer
Follow this Question
Related Questions
loop for perimeter of game board 0 Answers
Break the loop when there are no more questions 0 Answers
How to make a function wait (**I have looked elseware and havent found a well explained solution**) 0 Answers
Unity update does not be called when lock screen 0 Answers
Unity WaitForSeconds Not Working Inside Update or a Loop 2 Answers