- Home /
Making Fire Rate for an Input.GetButton
Hi Guys.
I've tried every thing i can but any method i use i get the same result.
public int damage = 10;
public float firerate = 0.5f;
public float nextfire = 0.0f;
void Shoot(){
if (Input.GetMouseButton (0) && Time.time > nextfire ) {
nextfire = Time.time + firerate;
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (new Vector3 (Screen.width * 0.5f, Screen.height * 0.5f, 0f));
if (Physics.Raycast (ray, out hit, 10000)) {
hit.transform.SendMessage ("applydamage", damage, SendMessageOptions.DontRequireReceiver);
Debug.Log("BANG!");
}
}
}
i'm calling the shoot function every frame but all i get in the log it gets called 4 times roughly every second. why is it being called 4 times each log? also the sendmessage ("applydamge") isn't being called properly.
am i doing doing something wrong? is there any other method i could try?
thanks
Can you try this? It usually helps me.
public int damage = 10;
public float fireRate;
float countdown;
void Update() {
if (Input.GetButton (0) && countdown <=0) {
//Do stuff
countdown = fireRate;
}
countdown -= Time.deltaTime;
}
What this does is set the temp variable 'countdown' to a 'read-only' like variable 'fireRate'. The countown is subtracted by Time.deltaTime, which is the time (seconds) since the last frame (this way if you lag, it still keeps that time). Once countdown gets to 0, then it fires.
Depending on what kind of gun, a machine gun may be 0.08 - 0.1 (10 shots per second).
Tell me what happens.
Edit: Are you sure you don't have the script on any other Game Objects in your scene? Only thing I can think of besides what I posted above.
thanks! it works perfectly. sorry i took so long to reply. I would up vote your answer but i cant find the option.
Thanks again.
Answer by stulleman · Aug 04, 2015 at 11:40 PM
Try Input.GetMouseButtonDown(0).
Also you should check for Time.time >= nextfire, not Time.time > nextfire.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Inheritance in C# and Unity3d 1 Answer
Mouse targeting error 1 Answer
How do I seed the random number generator myself and still get pseudorandom values? 2 Answers