I have a gun and need it to fire when I am holding down the left mouse button until a specific number of bullets fired is reached, then i reload. The script I have right now Instantiates a sphere and adds a force to it, but its only a one shot and doesnt have the bullet limit or reload function. I can add the reload and bullet limits myself i think, but im really stuck on the fire rate.
3 Answers
3I tend to use Time.deltaTime and Mathf.Max like so:
float timeTillNextShot = 0;
void Update()
{
timeTillNextShot = Mathf.Max(timeTillNextShot - Time.deltaTime, 0); //never go below 0
if(timeTillNextShot <= 0) //Add condition to check if we're firing here
{
timeTillNextShot = timeBetweenShots; //reset
fireAShot();
}
}
Just use a bool check with InvokeRepeating().
public bool mousePressed = false;
public float timeBetweenShots = 0.2f;
public int shotsPerClip = 30;
private bool runOnce = false;
void Update()
{
if(Input.GetMouseDown(0)){
mousePressed = true;
}
if(Input.GetMouseUp(0)){
mousePressed = false;
}
if(mousePressed){
if(shotsPerClip>0&&!runOnce){
InvokeRepeating("ShootGun", 0, timeBetweenShots);
runOnce=true;
}
}else{
CancelInvoke();
runOnce=false;
}
}
public void ShootGun(){
//do all shooting functions
if(shotsPerClip<=0){
CancelInvoke();
//call reload function
}
}
Look at this:
Gives you the actual firing code too.
Hey thanks!
– superpentil