I’m trying to do a continous shooting system, but as well when I press the button once it would only shoot once. And if a button is pressed in between attacks, when the attackDelay would end it would shoot again. I managed to do it, but it seems insufficient with four booleans. Maybe it’s possible to make it better? Would appreciate any help.
public class PlayerAttack : MonoBehaviour
{
[SerializeField] private float PistolAttackDelay = .5f;
[SerializeField] private GameObject Bullet;
[SerializeField] private Transform BulletSpawnPoint;
private bool CanAttack = true;
private bool isAttackHeld;
private bool AttackPressed = false;
private bool AttackReleased = false;
//When left mouse button is pressed this method is called
public void PistolAttack()
{
if (CanAttack)
{
isAttackHeld = true;
StartCoroutine(ShootBullet());
}
// Else method is called when mouse is pressed between the attacks(when pistolAttackDelay
// hasn't ended)
else
{
AttackPressed = true;
isAttackHeld = true;
}
}
IEnumerator ShootBullet()
{
CanAttack = false;
while (isAttackHeld)
{
Instantiate(Bullet, BulletSpawnPoint);
yield return new WaitForSeconds(PistolAttackDelay);
if (AttackReleased)
{
AttackReleased = false;
break;
}
}
if (AttackPressed)
{
AttackPressed = false;
if (!isAttackHeld)
AttackReleased = true;
isAttackHeld = true;
StartCoroutine(ShootBullet());
}
else
CanAttack = true;
}
// When mouse button released this method is called
public void CancelAttack()
{
isAttackHeld = false;
}
}