- Home /
GetMouseButtonDown(1) true in multiple frames
script is only on one object, it is GetMouseButtonDown(1) and still it is returning true sometimes once, twice or even three times.
if (Input.GetMouseButtonDown(1))
{
{
Ray r = Camera.main.ScreenPointToRay(new Vector3(Screen.width / 2, Screen.height / 2));
RaycastHit hit;
if (Physics.Raycast(r, out hit, 50, groundMask))
{
Quaternion targetRotation;
if (startRotation == SpawnType.Global)
targetRotation = Quaternion.identity;
else if (startRotation == SpawnType.Relative)
targetRotation = Quaternion.Euler(0, cameraController.transform.rotation.eulerAngles.y, 0);
else
targetRotation = RightClickSpawnStartRot;
Instantiate(RightClickSpawn, hit.point, targetRotation);
}
}
}
I have absolutely no idea how can that happen. Also it's not just now and with right click. It's like this ALL THE TIME. Any suggestions why?
Answer by Bunny83 · Aug 12, 2017 at 06:30 PM
There are only three possible reasons that come to my mind:
Maybe you don't execute that code in Update but in some other callback that may be called several times per frame. We can't see where that code snippet has been placed...
Maybe you somehow manually call Update from somewhere else. So Update effectively runs several times per frame. You should never call any of the Unity callbacks yourself.
Maybe you have attached that script to several objects in your scene. Each script instance works on it's own. So when you press down the mouse button, each script will recognise this event and execute the code inside the if statement.
You can add a simple Debug.Log to check all cases at once:
if (Input.GetMouseButtonDown(1))
{
string s = transform.name;
Transform t = transform.parent;
while (t != null)
{
s = t.name + "/" + s;
t = t.parent;
}
Debug,Log("MouseDown " + Time.frameCount + " : " + s);
//....
This will tell you:
the exact name of the object this script is attached to, including the hierarchy path
the frame number this code is executed. If the code is executed several times during one frame you will see the same number several times. Usually you should never see a duplicate number.
From where this debug log was called. Just check the stacktrace in the console. It tells you exactly from which method / method hierarchy this log was created.
If you see several logs with the same frame number and you can't figure out what might be the reason, just copy all logs with the same number and post them as a comment here. Keep in mind to copy the whole log entry including the stacktrace.
Your answer
Follow this Question
Related Questions
Using Input.mouseposition to instantiate 1 Answer
C# moveOnMouseClick Rotation 2 Answers
Simulate a mouse Click? 2 Answers
Multiple Cars not working 1 Answer