0
\$\begingroup\$

I have a While loop that runs when the mouse is pressed and it look like this:

while (mouseClick.ReadValue<float>() != 0)
{
   //Do something
}

This works but I want this to work on mobile instead so I am trying to change this to when a finger is touching the screen. I tried this code:

    while (touchControls.Touch.TouchPosition.ReadValue<Vector2>() != Vector2.zero)
    {
        //Do something
    }

That loop starts to run when a finger presses the screen, but it never stops. And touchControls.Touch.ReadValue() != 0 didn't work either. So how can I make it work like I want?

Thanks.

\$\endgroup\$
3
  • \$\begingroup\$ I'm assuming you have a yield instruction somewhere in that loop? It might be helpful to show that explicitly. \$\endgroup\$ Commented May 14, 2022 at 11:20
  • \$\begingroup\$ Do you mean this line: yield return null; ? \$\endgroup\$ Commented May 14, 2022 at 11:33
  • \$\begingroup\$ That is indeed a yield instruction. \$\endgroup\$ Commented May 14, 2022 at 12:23

1 Answer 1

1
\$\begingroup\$

One way is to access the InputSystem more directly.

You might be looking for TouchPhase or use the Finger combined with the EnhancedTouch.

using UnityEngine;
using UnityEngine.InputSystem.EnhancedTouch;
using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch;

public class TouchDemo : MonoBehaviour
{
    private void OnEnable()
    {
        EnhancedTouchSupport.Enable();
    }

    private void OnDisable()
    {
        EnhancedTouchSupport.Disable();
    }

    private void Update()
    {
        foreach (var touch in Touch.activeTouches)
        {
            // Only respond to first finger
            if (touch.finger.index == 0 && touch.isInProgress)
            {
                // TODO
            }
        }
    }
}

Edit: See the Touch struct for more information about the various states of a Touch.

\$\endgroup\$
2
  • \$\begingroup\$ Thanks that answer helped me, but it seems like "inProgress" should be changed to "isInProgress". \$\endgroup\$ Commented May 15, 2022 at 11:40
  • \$\begingroup\$ You are absolutely right! My bad. I've corrected it now. \$\endgroup\$ Commented May 15, 2022 at 16:41

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.