How can I autofire a ships gun every half second C#
I am making an oldfashioned sci-fi style shootemup and I want to make the main gun fire about every 0.5 seconds. This is what I have so far. using UnityEngine; using System.Collections;
public class laserblast : MonoBehaviour {
public Rigidbody laser;
public Rigidbody ship;
void Update () {
if (Input.GetKey("d"))
{
Instantiate (laser,ship.position,ship.rotation);
}
}
}
as you can see, when I press "d", laser fires from the ship. My problem is that another laser fires every frame and I would like to know how to control that so the laser comes in only every half second. Thank you.
Answer by GiyomuGames · Oct 20, 2015 at 02:18 AM
You should add variables "timeAtLastShot" and "minTimeBetween2Shots" (.5f is you want .5 seconds).
Then you do:
if (Input.GetKey("d") && (Time.time - timeAtLastShot) >= minTimeBetween2Shots)
{
Instantiate (laser,ship.position,ship.rotation);
timeAtLastShot = Time.time;
}
ops Sorry. I have seemed to forgotten about you. O$$anonymous$$, I tried what you suggested but there was an error somewhere. I searched up Time.time and I got this
public class ExampleClass : $$anonymous$$onoBehaviour {
public GameObject projectile;
public float fireRate = 0.5F;
private float nextFire = 0.0F;
void Update() {
if (Input.GetButton("Fire1") && Time.time > nextFire) {
nextFire = Time.time + fireRate;
GameObject clone = Instantiate(projectile, transform.position, transform.rotation) as GameObject;
}
}
}
and that worked just fine. What you suggested didn't exactly work but it pointed me in the right direction so thank you.
Ok cool! The important thing is that you sorted out your problem.