Touch Inputs in Unity3D

This is the one of the most discussed topics in many forums. Even though Unity3D is a multi platform game engine and supports all the mobile devices, the touch input with Unity3D is still tricky and not so easy to achieve. Even when attempted, many a times its not a smooth user experience and sometimes quirky and laggy. After many trials and errors I have come across a way to get the touch input work and I am sharing my way with you. Hopefully it will be of some use to you guys and may be you can take it a step further and can modify it according to your needs.

Please not that this Touch Input is for “Tap Detection” only including Multiple Finger Taps, as most of the devices can now detect upto 5 fingers at a time.

I assume that everyone is familiar with the Unity3D layout and ca navigate themselves around the software. This tutorial is applicable for both Unity3D v4 and Unity3D v5. The code written is in C# and if anyone is using JavaScript or Unity Script, I highly recommend you to shift to C# as it is much more flexible and widely used language across Unity3D.

1> Open up a new project and Create a C# Script and name it TouchInput.cs

2> Follow the code below and copy-paste it in your script file. I will explain each line of the code below.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class TouchInput : MonoBehaviour {
    
    public LayerMask touchInputMask;
    
    private List <GameObjecttouchList = new List<GameObject>();
    private GameObject[] touchesOld;
    private RaycastHit hit;
    
    
    // Update is called once per frame
    void Update () 
    {
        

        
        if(Input.touchCount > 0)
        {
            touchesOld = new GameObject[touchList.Count];
            touchList.CopyTo(touchesOld);
            touchList.Clear(); 
            
            
            foreach(Touch touch in Input.touches
            {
                
                Ray ray = camera.ScreenPointToRay(touch.position);
                
                
                if(Physics.Raycast(ray,out hittouchInputMask))
                {
                    GameObject reciepient = hit.transform.gameObject;
                    touchList.Add(reciepient);
                    
                    if (touch.phase == TouchPhase.Began)
                    {
                        reciepient.SendMessage("OnTouchDown"hit.pointSendMessageOptions.DontRequireReceiver);
                    }
                    
                    if (touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved)
                    {
                        reciepient.SendMessage("OnTouchStay"hit.pointSendMessageOptions.DontRequireReceiver);
                    }
                    
                    if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
                    {
                        reciepient.SendMessage("OnTouchEnd"hit.pointSendMessageOptions.DontRequireReceiver);
                    }
                    
                }
            }
            
            foreach (GameObject g in touchesOld)
            {
                if(!touchList.Contains(g))
                {
                    g.SendMessage("OnTouchEnd"hit.pointSendMessageOptions.DontRequireReceiver);
                }
            }
        }

        #if UNITY_EDITOR
        
        if(Input.GetMouseButton(0) || Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0))
        {
            touchesOld = new GameObject[touchList.Count];
            touchList.CopyTo(touchesOld);
            touchList.Clear(); 
            
            
            Ray ray = camera.ScreenPointToRay(Input.mousePosition);
            
            
            if(Physics.Raycastrayout hit100ftouchInputMask.value))
            {
                GameObject reciepient = hit.transform.gameObject;
                touchList.Add(reciepient);
                
                if (Input.GetMouseButton(0) || Input.GetMouseButtonDown(0))
                {
                    reciepient.SendMessage("OnTouchDown"hit.pointSendMessageOptions.DontRequireReceiver);
                }
                
                if (Input.GetMouseButtonUp(0))
                {
                    reciepient.SendMessage("OnTouchEnd"hit.pointSendMessageOptions.DontRequireReceiver);
                }
            }
            
            foreach (GameObject g in touchesOld)
            {
                if(!touchList.Contains(g))
                {
                    g.SendMessage("OnTouchEnd"hit.pointSendMessageOptions.DontRequireReceiver);
                }
            }
        }
        
        #endif
        
    }
}

2.a> You will have to add the using System.Collection.Generic (line 3) first as we are using the it

2.b> Next we create a Layer Mask (line 7) as to make sure that only game object inside that layer gets activated by touch scripts. Its a good practice to do.

2.c> Next we write a code to detect touch inputs and then we send message to the game object which has been tapped or are being tapped.

3> After that inside the Update function, we write a code for Editor so that user can test their game inside the Unity Editor as touch call button will not be called from inside Editor. It is the same code but its been specified only for Unity_Editor as Mobile devices are capable of detecting GetMouseButton(0) and GetMouseButtonDown(0) as a first tap and therefore it will cause conflict. So make sure that this code is only called inside the Editor.

4> Next We need to drag the TouchInput.cs to a “Camera” and you will see a new Drop Down Menu option called Touch Input Mask

5> Now we must make a new Layer callled “Touch Input” and select that layer from the Drop Menu Option in the TouchInput Script inside Camera (See Screenshot Below)

TouchInpScreen01

6> Next Create some cube inside the game scene and add a 3D Box Collider to it. The reason to add the 3D Box Collider is to be able to detect the collision when the Button or Finger is Tapped.

7> After that make sure that you have selected the layer of that 3D Cube as Touch Input or the Input Script wont detect the tap detection.

8> Next we write a code which will say the Cube what to do when the Button or Finger is tapped on it

9> Make a new C# Script and called it Button.cs

10> Follow the code below and copy-paste the content

using UnityEngine;
using System.Collections;

public class Buttton : MonoBehaviour {

    void OnTouchDown()
    {
        print("Button Down");
    }


    void OnTouchStay()
    {
        print("Button Pressed");
    }

    void OnTouchEnd()
    {
        print("Button End");
    }
}

10.a> The above code is pretty self explanatory as we have written function of each call action.

11> You can use the same script in any GameObject and can be pretty sure that any action which you have written inside the Call function will be called as its tapped or pressed.

Hope you enjoyed the tutorial and in case you face any problem just write in the comment box and I will check it out

  1. Works great, thank you!

  1. No trackbacks yet.

You must be logged in to post a comment.