- Home /
delay between shots
i want to put a delay between every shot here is the script using JetBrains.Annotations; using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine;
public class shootingforshutgun : MonoBehaviour
{
public Transform ponit;
public float Speed =10f;
public GameObject bullet;
bool canshot = false;
int Bullets = 4;
int currentbullet;
bool reloading = false;
void Start()
{
currentbullet = Bullets;
}
// Update is called once per frame
void Update()
{
if(currentbullet <= 0 && !reloading )
{
StartCoroutine(wait());
return;
}
if (Input.GetButtonDown("Fire1"))
{
if (!canshot)
{
A();
A();
A();
A();
currentbullet -= 1;
canshot = false;
StartCoroutine(waitbetweenshoot());
}
}
}
public void A()
{
if (reloading)
return;
if (!canshot)
{
float x = Random.Range(-4f, 4f);
float y = Random.Range(-4f, 4f);
Vector3 a = new Vector3(x, y);
Vector3 c = a + ponit.position;
Instantiate(bullet, c, transform.rotation);
StartCoroutine(waitbetweenshoot());
}
}
IEnumerator wait()
{
reloading = true;
yield return new WaitForSeconds(2f);
currentbullet = Bullets;
reloading = false;
}
IEnumerator waitbetweenshoot()
{
yield return new WaitForSeconds(2f);
canshot = true;
}
}
Comment
Answer by Baschti-aus-s · May 28, 2020 at 10:09 PM
I guess you want to press the mouse button once and than fire a burst of 4 shots and than reload, right? You can convert your methode A() to a coroutine:
IEnumerator A()
{
if (reloading)
return;
canshot = true;
while (currentbullet > 0)
{
float x = Random.Range(-4f, 4f);
float y = Random.Range(-4f, 4f);
Vector3 a = new Vector3(x, y);
Vector3 c = a + ponit.position;
Instantiate(bullet, c, transform.rotation);
currentbullet --;
yield return new WaitForSeconds(2f);
}
canshot = false;
}
With the call
if (Input.GetButtonDown("Fire1"))
{
if (!canshot)
{
StartCoroutine(A());
}
}
The coroutine waitbetweenshoot() becomes obsolete than.
Your answer
Follow this Question
Related Questions
2D Shooting Delay with Animation 2 Answers
How to Sync bullet spawn with shoot animation 0 Answers
Shooting & Animation Problem 1 Answer
Shot Delay between button press. c# 2 Answers
Gun reload and clip size 0 Answers