0

I am coding for a scene where QR Code is generated according to the last position I'm touching on the screen but when I touch the button for generating the code, the last position becomes my button.

Is there a way where the 'Input.touchCount' doesn't take the button click as touch count without disabling the function of the button?

P D
  • 23
  • 8

1 Answers1

0

Check if you are hitting UI and if so ignore the touch

e.g.

public Vector2 lastTouchPosition;

// Optional some random initialization in case you directly hit the button
private void Start ()
{
    lastTouchPosition = new Vector2 (Random.Range(0f, Screen.width, Random.Range(0f, Screen.height));
}

void Update ()
{
    if(Input.touchCount > 0)
    {
        var touch = Input.GetTouch(0);

        if(!EventSystem.current.IsPointerOverGameObject())
        {
            lastTouchPosition = touch.position;
        }        
    }
}

By default the Eventsystem takes all UI elements into account that have Raycast Target enabled (default for all UI elements like Image, Text, TMP_Text etc)


You you are using the new InputSystem refer to this post

derHugo
  • 83,094
  • 9
  • 75
  • 115
  • If we want to take the position value, how to decide if it should be "touch" or "lastTouchPosition"? – P D Feb 27 '23 at 06:52
  • @PD You always will want to get the `lastTouchPosition` of course. When you click the button it will ignore that touch so you get the last touched position before touching any UI – derHugo Feb 27 '23 at 10:29
  • private void EncodeTextToQRCode() { string textWrite = theTouch.position.ToString(); Color32[] convertPixelToText = Encode(textWrite, storeEncodedTexture.width, storeEncodedTexture.height); storeEncodedTexture.SetPixels32(convertPixelToText); storeEncodedTexture.Apply(); rawImageReceiver.texture = storeEncodedTexture; } I have to put this code in condition. If the touch is on NON UI position, it will take the current position, but if it is over UI, then it will take the last position that was clicked – P D Feb 28 '23 at 07:29