multi screen tap

Hi guys, In my game I want the player to tap a cage multiple times to set an elephant free.
I’ve set up the following code and included a counter. When the collision box is tapped I want the tap count to increase, then when the tap count gets to 5 I want the cage door to open.

Here is my c# code

using UnityEngine;
using System.Collections;

public class CageLv0 : MonoBehaviour {
    public int tapCount; //how many times has the button been tapped?
    // Use this for initialization
    void Start () {
    }
   
    // Update is called once per frame
    void FixedUpdate () {
   
    if (tapCount == 2)
        {
            Destroy(gameObject);
        }

    if (Input.touchCount == 1) //if the button is pressed
    {
        Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position); //sets the screen to worldpoint
        Vector2 touchPos = new Vector2(wp.x, wp.y); //declare x and y of the world point
           
        if (collider2D == Physics2D.OverlapPoint(touchPos)) //if the collider is touched
        {
                tapCount ++;
        }
    }

}
}

The weird thing is, if I tap the cage once, the door is deleted. Not sure how this happens, I’d expect nothing to happen if it didn’t work.
What am I missing?

Cheers guys

You’re not checking which phase of the touch itself is happening, so it’s probably registering both when you touch the screen and also when you lift your finger.

Check the documentation for Input.GetTouch : Unity - Scripting API: Input.GetTouch

Ah, okay. So does that mean i’ll have to use a different method for detecting touches?
Or can I state what happens during each touch type and insert it into my existing touch detection code?
Sorry, i’m not very good at programming so I get easily confused :stuck_out_tongue:

You can define which touch types you want to process. If you look at the link I gave you, you’ll see that they are not only using Input.touchCount to check for touches, but are also checking the Input.GetTouch(i).phase.

So in your case, instead of if (Input.touchCount == 1) try this : if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began )

This way the counter will increment only when there is one finger pressing the screen and only when you begin touching the object.

That makes sense. don’t know how I didn’t see that. Thank you! :slight_smile: