- Home /
Raycast repeats multiple times
I am trying to lose damage once when i click using raycast and i use the debug as a test, and with one click it displays 5 debug logs and loses lots of health...
public class Crosshair : MonoBehaviour
{
public float range = 8.0f;
public float damage = 10.0f;
void Start ()
{
Screen.showCursor = false;
}
void Update ()
{
Screen.lockCursor = true;
if(Input.GetMouseButton(0))
{
Fire();
}
}
void Fire ()
{
Ray ray = new Ray(transform.position + transform.forward /2 , transform.forward);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, range))
{
if (hit.collider.gameObject.tag == "Destructible")
{
Debug.Log("hi");
hit.collider.gameObject.GetComponent<Destructible>().ApplyDamage(damage);
}
}
}
}
Answer by Tomer-Barkan · Oct 11, 2013 at 07:51 PM
your problem is here:
if(Input.GetMouseButton(0)){
This checks if the button is currently pressed. In the time it takes you to release the button after pressing, the GetMouseButton() function will return true. Since frames are very fast, it will be 4-5 frames that the button is still pressed before you release it (even if you're fast, computer is faster).
There's a method called GetMouseButtonDown()
which will only return true in the first frame that the button is pressed. This means only ones per key press.
So change it:
if(Input.GetMouseButtonDown(0)){
Answer by clunk47 · Oct 11, 2013 at 07:49 PM
Use GetMouseButtonDown instead of GetMouseButton, so that you only call Fire() once per click, instead of calling it every frame that the mouse button is down.
Your answer
![](https://koobas.hobune.stream/wayback/20220613115749im_/https://answers.unity.com/themes/thub/images/avi.jpg)