Hello fellow Unity users.
I’m currently creating a game as a school project and it’s going to be a top-down shooter.
I wanted to create a variety of weapons, and some weapons will have a burst fire.
What I have right now is a weapon that will fire three bullets very fast, and the script is working as planned.
One thing is bothering me though.
I know there is a better way to write the code below.
Can you guys please help me figure it out?
This is not the whole script. This code is a part in a bigger script, so don’t worry about the bullet velocity.
I have only included the function that shoots the bullets, works exactly like planned, but it does not look good.
The script was written in C#.
public float BulletFireRate;
public GameObject ProjectilePrefab;
void Update()
{
if (Input.GetKeyDown("mouse 0"))
StartCoroutine(Shoot());
}
IEnumerator Shoot()
{
Vector3 Position = new Vector3(transform.position.x,
transform.position.y + ProjectileOffset,
transform.position.z);
Instantiate(ProjectilePrefab, Position, Quaternion.identity);
yield return new WaitForSeconds(BulletFireRate);
Instantiate(ProjectilePrefab, Position, Quaternion.identity);
yield return new WaitForSeconds(BulletFireRate);
Instantiate(ProjectilePrefab, Position, Quaternion.identity);
yield return new WaitForSeconds(BulletFireRate);
}
I want you to know that I’m only using this piece of code as a last resort, I have tried many other things that did not work.
Thanks in advance!
Edit:
I forgot to use a for-loop in the coroutine, anyway here’s the new script for anyone who wants some variety.
private float BulletFireRate = 0,1f;
public GameObject ProjectilePrefab;
public int NumberOfBullets = 3;
private float ProjectileOffset = 1.3f;
void Update ()
{
if (Input.GetKeyDown("mouse 0"))
StartCoroutine(Shoot());
}
IEnumerator Shoot()
{
Vector3 Position = new Vector3(transform.position.x,
transform.position.y + ProjectileOffset,
transform.position.z);
for (int i = 0; i < NumberOfBullets; i++)
{
Instantiate(ProjectilePrefab,
Position,
Quaternion.identity);
yield return new WaitForSeconds(BulletFireRate);
}
}