- Home /
Trying to get a shoot function working in unity using instantiate and it isn't working.
Hello there I am trying to make a gun by simply instantiating a bullet object when the player clicks the left mouse button. But my script isn't working and I for the life of me cannot figure out what the problem is. I am not getting any compiler errors and I cannot see any issues in the logic. I am trying to used fixed delta time to create a timer that limits how often the player can shoot. I am not interested in reloads just rate of fire.
public class PlayerShoot : MonoBehaviour
{
public string fireButton = "Fire1";
public float fireForce = 500.0f;
public GameObject Bullet;
private float RateOfFire = 5.0f;
private float TimerForBullets = 0;
// Update is called once per frame
void FixedUpdate ()
{
if (Input.GetButtonDown(fireButton))
{
TimerForBullets = RateOfFire;
TimerForBullets -= Time.deltaTime;
if (TimerForBullets > 0)
{
return;
}
if (TimerForBullets < RateOfFire)
{
Vector3 firePosition = transform.position + transform.forward;
GameObject b = GameObject.Instantiate(Bullet, firePosition, transform.rotation) as GameObject;
if (b != null)
{
Rigidbody rb = b.GetComponent<Rigidbody>();
Vector3 force = transform.forward * fireForce;
rb.AddForce(force);
}
}
}
}
}
Answer by tpusch · May 10, 2016 at 04:38 PM
It seems to be because your TimerForBullets
only decrements every first frame the user presses the fire button. For example if Time.delta time is .1 sec you would have to press your mouse button 50 times before you fired a single bullet. Instead keep your timer out of the input check like. Also as I read closer you actually reassign the rate of fire to your timer every time you click which means it would never be reduced by more than .1 with my example time, that should only be reset if you actually fire a bullet.
void Update ()
{
TimerForBullets -= Time.deltaTime;
if (Input.GetButtonDown(fireButton))
{
if (TimerForBullets <= 0)
{
Vector3 firePosition = transform.position + transform.forward;
GameObject b = GameObject.Instantiate(Bullet, firePosition, transform.rotation) as GameObject;
if (b != null)
{
Rigidbody rb = b.GetComponent<Rigidbody>();
Vector3 force = transform.forward * fireForce;
rb.AddForce(force);
}
TimerForBullets = RateOfFire;
}
}
}
2 final notes: I would put it in the Update loop instead of FixedUpdate as that would give you a quicker response to user input. I also removed the early return portion, which is unnecessary, if the if (TimerForBullets <= 0)
fails it will pass out of the function anyway and later you may want more logic in your Update after your firing.
Your answer
Follow this Question
Related Questions
Bullet not always shooting in forward direction. Code included. 2 Answers
2D platformer firing left and right, help! 1 Answer
Instantiate Object at the extreme end of the object 0 Answers
How to add random force/Rotation to bulletEject. 1 Answer
How are you able to use a Transform argument for Instantiate? 2 Answers