- Home /
Fire limit in a Space shooter?
I have a script for a 2d space shooter game, and I want to make a limit so only 3 bullets are allowed on screen at a time If you need it, here's the script:
using UnityEngine; using System.Collections;
public class PlayerLaser : MonoBehaviour
{
float speed;
public GameObject Laser;
public GameObject LaserPositionA;
// Use this for initialization
void Start ()
{
speed = 15f;
}
// Update is called once per frame
void Update()
{
//get the bullet's current position
Vector2 position = transform.position;
if (Input.GetKeyDown("space"))
{
GameObject bullet01 = (GameObject)Instantiate(Laser);
bullet01.transform.position = LaserPositionA.transform.position;
}
//compute the bullet's new position
position = new Vector2(position.x, position.y + speed * Time.deltaTime);
//update the bullet's position
transform.position = position;
//this is the top-right point of the screen
Vector2 max = Camera.main.ViewportToWorldPoint(new Vector2(1, 1))
;
if (transform.position.y > max.y)
{
Destroy(gameObject);
}
}
}
Thank you!!
Answer by roman_sedition · Nov 17, 2016 at 08:07 AM
Logic wise I think you should keep a reference to each bullet you instantiate into a List.
In your shooting method you do a conditional check for if the contents of the List has less than 3 active bullet gameObjects still in the list, if it is less than 3 you can shoot again. Destroyed bullets will come up as null in the list.
Then you just remove null elements in the list to keep your list tidy so it can be processed through quickly.
if (transform.position.y > max.y)
{
Destroy(gameObject);
}
This above code looks like it might be a problem? It destroys whatever 'this' gameObject is, but I'm assuming you want to destroy the instantiated Laser instead, which is why you need a reference to each Laser you instantiate.
Let's say you have a list called lasers.
public List<GameObject> lasers = new List<GameObject>();
Which you add to when you instantiate the bullets.
if (Input.GetKeyDown("space"))
{
GameObject bullet = (GameObject)Instantiate(Laser);
bullet.transform.position = LaserPositionA.transform.position;
lasers.Add (bullet);
}
You can place a method like this in Update() to make it destroy those lasers when ever they reach what the defined max.y is.
void LasersOffScreen()
{
foreach(GameObject laserBullet in lasers)
{
if ( laserBullet.transform.position.y > max.y)
{
Destroy(laserBullet);
}
}
}