Instantiate bullet in time interval for "rifle".

Help me here guys, please…

I made this script for my cannon:

@script ExecuteInEditMode()

var bulletPrefab: Transform ;
var bulletSpeed: float = 60;
var buttonX: int = 0;
var buttonY: int = 0;
var rifle: boolean = false;
var nextShotTime : float = 0.0;
var timeBetweenShots : float = 2.0;

function Update()
{
 if(Input.GetKeyDown(KeyCode.M))
 {
 if(rifle)
 {
 rifle = false;
 }
 else
 {
 rifle = true;
 }
 }
 if (Input.GetButtonDown("Fire1"))
 {
 if(rifle)
 {
 Shoot();
 }
 else
 {
 if (nextShotTime <= Time.time)
          {
              Shoot();
              nextShotTime = Time.time + timeBetweenShots;
          } 
 } 
 
 }
}

function Shoot()
{
    var shoot = Instantiate(bulletPrefab,GameObject.Find("Spawn").transform.position,GameObject.Find("Spawn").transform.rotation);
 shoot.rigidbody.AddForce(GameObject.Find("Spawn").transform.forward * bulletSpeed);
}

function OnGUI()
{
if(rifle)
 {
 GUI.Box (Rect ( 10,40,150,30), "rifle");
 }
 else
 {
 }
}

For the normal mode it is doing what i want it to do, shooting the bullet only from time to time (2 seconds in this case) even if i press the fire button more than that… Now… How do I get my rifle mode to work… So far it only makes it possible to shoot without the time interval set but i want it to do the opposite, instantiate automatically the prefab from time to time, in this case, every 0.02 seconds or so…
Can you help guys? Thanks a lot.

I have the same question. But 8 years later. It would be interestant to see your 8 year old project!

Just change it to buttonPressed instead of ButtonDown. “Down” signifies an “edge” movement, did the button just go down or up. “Pressed” is for a button being held.

bool triggerHeld = Input.GetButtonPressed("Fire1");

then similar to your current code…

if (triggerHeld && (nextShotTime <= Time.time))
           {
               Shoot();
               nextShotTime = Time.time + timeBetweenShots;
           }