How to correctly detect touch and apply single action?

Hello everyone,

I have a game object (in a 2D game) that will jump when the space bar is hit (on PC and so) or when the screen is touched (on mobile devices and so).

When I tried the game on PC, the game object jumps as expected. However, when I get my game on an Android device, my game object jumps multiple times higher!

To debug my code I introduced some variable that counts the number or requested jumps. The number was always 1 on PC (no surprise here) and to my surprise it was almost always 2 on Android.

Below is the code on my game object:

private void Update()
    // Make the player jumps
    if ((Input.GetKeyDown(this.JumpButton) || Input.touchCount == 1) && this.isGrounded)
        this.didJump = true;

        // Just for debugging
        this.maximumJumpOrders = this.maximumJumpOrders < this.totalJumpOrders ? this.totalJumpOrders : this.maximumJumpOrders;

private void FixedUpdate()
    this.isGrounded = Physics2D.Linecast(this.transform.position, this.groundCheck.position, 1 << LayerMask.NameToLayer("GroundLayer"));

    if (this.didJump)
        this.didJump = false;
        this.totalJumpOrders = 0;

        this.rigidbody2D.AddForce(this.transform.up * this.JumpPower);

My questions are:

  1. How to correctly detect touch and apply single action? It seems like the force is applied multiple times (even more than twice from the height of the jump)
  2. How to detect that the player is still touching the screen so do not do anything until they remove their finger and touch again?
  3. Is their any guidelines on how to handle touch events with Unity?

Bear with me, I’m still new to Unity and still finding my way around :slight_smile:

P.S. I tested the game on a Windows 8 machine and on Android 4.2 running on the original Samsung Galaxy S (CyanogenMod ROM)

Hi! Your problem is that you are checking always if there is a touch, so every frame it restarts the didJump variable to true and causes it to keep jumping.

you should check if the touch is in its beginning phase:

if(Input.TouchCount == 1)
    if(Input.GetTouch(0).phase == TouchPhase.Began)
        //your code here will be called only once per touch

you can check here for more info on touches