Search code examples
androidunity-game-enginepositiontouch

Unity Touch.Phase.Position always returning (0,0,0)


So I have the below code

private Touch touch;
private Vector2 beginTouchPosition;
private Vector2 endTouchPosition;
public GameObject timeText;
public GameObject CashText;

void Update()
{
    if (Input.touchCount > 0)
    {
        switch (Input.GetTouch(0).phase) 
        {
            case TouchPhase.Began:
                beginTouchPosition = touch.position;
                timeText.GetComponent<Text>().text = beginTouchPosition.y.ToString();
                break;

            case TouchPhase.Ended:
                endTouchPosition = touch.position;
                CashText.GetComponent<Text>().text = endTouchPosition.y.ToString();
                if (beginTouchPosition == endTouchPosition) 
                { 
                    //Do Stuff
                }
                break;
        }
    }
}

The problem with the code above is that timeText and cashText both display (0,0,0) meaning that it is saying that the position of began.position phase is always (0,0,0) and so is the end.position phase. even though they are definitely not.


Solution

  • Thats happend because you never assign anything to touch. So is empty

    if (Input.touchCount > 0)
    {
       touch = Input.GetTouch(0);
       switch (touch.phase)
       {
          .....
       }
    }