Code executes too many times

Hello,

I do have the following code in the Update

   void Update()
    {
        if (Input.GetMouseButton(0))
        {
            Vector2 _worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            RaycastHit2D _hit = Physics2D.Raycast(_worldPoint, Vector2.zero);
            if (_hit.collider != null)
            {
                    MakeMove(int.Parse(_hit.collider.name));
                    Debug.Log(int.Parse(_hit.collider.name));
         }
        }
    }

When I look in the console, whenever I hit (click) some gameobject on the screen, the Debug outputs 4-6 times of that gameObject’s name. That means the function MakeMove has been called 4-6 times, which is not the right behavior I’m looking for. I want it to be fired only once, when it has been clicked, until the next time when it will be clicked.
So, how to make it fire only once? but not 4-6 times? I do understand that is the behavior of Update, which runs every frame, but how can I make it work in my way?

Input.GetMouseButton(0) returns true every frame when the mousebutton is held down. Use Input.GetMouseButtonDown instead.

2 Likes

Wow, cool. It works as it should. One more question. When I’ll compile it for mobile phone, is that going to have the same behavior? Because I’m developing for Android phones…

No, for touch screens you should use Input.touches. Something like

if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began)
{ ... }
3 Likes

I agree with this, but it is worth nothing that a single touch is registered as mouse button 0, so technically his code will work on an android device as long as he doesn’t need multi-touch support in his application.

1 Like

As an alternative you can use the EventSystem. It pretty much does the same thing as the code in the OP. And its supported across platforms by default.

I’ve already killed most of my custom raycasters in favour of using the EventSystem to handle input.

1 Like

@Kiwasi ,

I’ve found the following in the learning section of Unity
http://unity3d.com/learn/tutorials/modules/intermediate/live-training-archive/events-creating-simple-messaging-system

I didn’t watch it but is that what you meant?