0
0
Unityframework~5 mins

Touch input basics in Unity

Choose your learning style9 modes available
Introduction

Touch input lets your app know when and where someone touches the screen. It helps make games and apps interactive on phones and tablets.

You want to detect when a player taps the screen to jump in a game.
You want to drag an object by touching and moving your finger.
You want to detect multiple fingers touching at the same time for gestures.
You want to respond when the user swipes across the screen.
You want to create buttons that react to finger touches.
Syntax
Unity
if (Input.touchCount > 0) {
    Touch touch = Input.GetTouch(0);
    if (touch.phase == TouchPhase.Began) {
        // Code for when touch starts
    }
}

Input.touchCount tells how many fingers are touching the screen.

Input.GetTouch(index) gets info about a specific touch.

Examples
This checks if the screen was just touched and prints a message.
Unity
if (Input.touchCount > 0) {
    Touch touch = Input.GetTouch(0);
    if (touch.phase == TouchPhase.Began) {
        Debug.Log("Finger touched the screen");
    }
}
This loops through all touches and prints their positions.
Unity
for (int i = 0; i < Input.touchCount; i++) {
    Touch touch = Input.GetTouch(i);
    Debug.Log($"Touch {i} position: {touch.position}");
}
This detects when a finger moves and shows how far it moved.
Unity
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved) {
    Vector2 delta = touch.deltaPosition;
    Debug.Log($"Finger moved by {delta}");
}
Sample Program

This program checks the first finger touching the screen. It prints messages when the touch starts, moves, or ends, showing the position or movement.

Unity
using UnityEngine;

public class TouchExample : MonoBehaviour {
    void Update() {
        if (Input.touchCount > 0) {
            Touch touch = Input.GetTouch(0);
            if (touch.phase == TouchPhase.Began) {
                Debug.Log($"Touch started at {touch.position}");
            } else if (touch.phase == TouchPhase.Moved) {
                Debug.Log($"Touch moved by {touch.deltaPosition}");
            } else if (touch.phase == TouchPhase.Ended) {
                Debug.Log("Touch ended");
            }
        }
    }
}
OutputSuccess
Important Notes

Touch positions are in pixels from the bottom-left corner of the screen.

Touch phases include Began, Moved, Stationary, Ended, and Canceled.

Use Input.touchCount to avoid errors when no fingers are touching.

Summary

Touch input lets you detect finger actions on the screen.

Use Input.touchCount and Input.GetTouch to read touches.

Check touch.phase to know if a touch started, moved, or ended.