- Home /
Left mouse button registers multiple clicks
Scenario: I want to be able to click on a card if it's not selected (and it is allowed to be selected) and move it up. Likewise, I would like to be able to click on a card if it is selected to move it down.
Issue: When I have the code to move the card up, given that it is allowed to be selected and that it is not currently selected, it works with no issues. It moves up as I expect and registers a single mouse click. However, when I add code to move the card back down if it is allowed to be selected and is currently selected, the card doesn't move. A little bit of debugging later, it looks like it's because it registers maybe two dozen mouse clicks, even though I'm using GetMouseButtonDown and clicking a single time.
I'm not sure what I'm doing wrong, but if someone could help, that would be awesome!
Code:
void Update()
{
GetMouseClick();
}
void GetMouseClick()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, -10));
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (hit)
{
if (hit.collider.CompareTag("Card"))
{
ClickCard(hit.collider.gameObject);
}
}
}
}
void ClickCard(GameObject card)
{
Selectable selectable = card.GetComponent<Selectable>();
if (selectable.CanSelect && !selectable.IsSelected)
{
card.transform.Translate(0, 0.75f, 0);
selectable.IsSelected = true;
print("Clicked from Not Selected.");
}
else if (selectable.CanSelect && selectable.IsSelected)
{
card.transform.Translate(0, -0.75f, 0);
selectable.IsSelected = false;
print("Clicked from Selected.");
}
}
Debug window:
Do you have more than one instance of the script that checks the mouse input in your scene?
You can check easily if you click on each log in the console. It should highlight the object responsible for that log in the inspector. Make sure they are not co$$anonymous$$g from different objects.
Nothing seems to be wrong with the code however to find out if the GetMouseClick() method or ClickCard() method is called anywhere else, just check if there is any other references to them, I know in VS you can simply right click on a method and select "Find all references". Also like the other comment mentioned, make sure you don't have it instantiated multiple times.
Answer by dwathen · Mar 26, 2021 at 03:16 AM
So, I was able to find the problem. As @MikeNewall and @smurfj3 mentioned, I had the script attached to all of the cards, which means it fired once for each script.
Thanks for your help!