Ok, so I’m doing a “space invaders”-type game. However, I want to NOT have rapid fire. Right now, when I press ‘space bar’ it fires a laser, every time I press it. What I want is to tell unity (using c#) that only 1 laser is able to be in play at a time.
An IF statements sounds like it would work nicely but I can’t seem to figure out something that’ll work cuz you can’t use booleans with gameobjects. I’m trying ‘states’ too but cant’ quite to get that down. :\
This is usually done by using a timer that blocks shooting during some time after each shot - like this:
public float interval = 0.2f;
float nextShot = 0.0f;
...
void Update(){
if (Input.GetKeyDown("space")){
if (Time.time >= nextShot){ // only shoot after interval
nextShot = Time.time + interval; // update nextShot
// shoot
}
}
}
EDITED: Ok, so you want only one projectile at a time. There’s an interesting Unity feature that help us doing that: when an object is destroyed, all references to it become null (I honestly don’t know how Unity does that, but it does!)
You can use this to know when a projectile is dead and enable a new shot:
public Transform projectile; // the projectile prefab
Transform shot; // save the last projectile instantiated
...
void Update(){
if (shot == null){ // only shoot if last projectile is dead
if (Input.GetKeyDown("space")){
shot = Instantiate(projectile, ...) as Transform; // save a reference to the projectile
...
}
}
}
You could save a reference to your projectile, then check to see if it’s dead, if so, destroy it and set your reference to the projectile to null.
If the reference is null, you can shoot another one…
In this case, you should not have the projectile destroy itself, but instead just set it’s Dead property to true after it collides, explodes, does damage or whatever, then the “Owner” of the projectile will destroy it.
Note that this is different from the way most projectiles are treated (ie, fire and forget).