I am trying to use IEnumerator to yield between bullet instantiations but it will not yield properly. I got it working perfectly at one point but broke it again later. I think the problem is my misunderstanding of how IEnumerator works.
If anyone knows of a better way for me to achieve my desired function please tell me.
Please have a look over my code and show me what I am doing wrong:
using UnityEngine;
using System.Collections;
public class scarh : MonoBehaviour
{
public Rigidbody projectile;
private bool shooting = false, reloading = false, canShoot = false;
private int z = 1;
public int currentAmmo = 20, speed = 500, maxAmmo = 20;
public float shootDelay = 5.0f;
void Start()
{
}
void reload()
{
// currentAmmo = maxAmmo;
}
// if(currentAmmo <= 0)
// {
// print ("Reloading!");
// reload ();
//Yield for 3 seconds
// yield return new WaitForSeconds(3);
//Set reload to false so you can shooting again
// print ("Reloading complete");
// reloading = false;
// }
IEnumerator TimedShooting()
{
//While player is shooting
while(shooting)
{
print ("Running IEnumerator");
//If there is a projectile
if(projectile)
{
//Instantiate projectile
Rigidbody newProjectile = Instantiate(projectile, transform.position,
transform.rotation) as Rigidbody;
//Give projectile velocity
newProjectile.velocity = transform.TransformDirection(new Vector3 (0, 0, speed));
//Remove 1 from currentAmmo
currentAmmo -= 1;
//Yield before next shot?
yield return new WaitForSeconds(shootDelay);
print ("Yielding");
}
}
}
void Update ()
{
//When holding down Fire1
if (Input.GetButton("Fire1"))
{
shooting = true;
StartCoroutine ("TimedShooting");
print ("Shooting: " + shooting);
}
//When Fire1 is released
if(Input.GetButtonUp ("Fire1"))
{
shooting = false;
//Set shooting to false
print ("Shooting: " + shooting);
}
//Switch fire mode when Z is pressed
if (Input.GetKeyDown(KeyCode.Z))
{
z = (z % 3) + 1;
print (z);
}
}
}