I'm currently trying to code a charge shot for a weapon, just like you'd see in a Mega Man game. However, while everything else seems to work just fine for the first shot, the next ones do not. It's like this: the coroutine I set up works just fine; makes you hold the button down for two seconds to fire off the charged shot. Great. But, after that, the charged shots fire off immediately with each GetButtonUp use. Think semi-auto fire, as fast as you can pull the trigger. Clearly, that won't do for a charged shot. I believe the issue is with the coroutine. They are only used once per script correct? So, how can I make it to where the coroutine can be used as many times as I want? I tried a while loop with yield, but it doesn't work. Just makes it fire off four or five charged shots in one button press, still semi-auto. Is it because I didn't put it in the right place? Or, is it not a good function to use for this altogether? Here is my current script:
public Transform chargeSpawn;
public GameObject chargeShot;
private float chargeTime = 0;
private float chargeRate = 2f;
public float fireRate1;
public float nextFire1;
void Update()
{
StartCoroutine(TimerRoutine());
}
IEnumerator TimerRoutine()
{
while (true)
{
if (Input.GetButtonDown("Fire1"))
{
yield return new WaitForSeconds(2f);
chargeTime += chargeRate;
}
else if (Input.GetButtonUp("Fire1") && Time.time > 2f)
{
Instantiate(chargeShot, chargeSpawn.transform.position, chargeSpawn.transform.rotation);
GetComponent().Play();
chargeTime = 0;
}
else if (Input.GetButtonUp("Fire1") && Time.time < 2f)
{
chargeTime = 0;
}
yield return new WaitForSeconds(5f);
}
}
↧