My previous (first) tutorial had a big success, so I though, I create another one. This is version 2.0. Enjoy it 😉 (This one is about detecting touched game objects)

If you didn’t read the previous tutorial you can read here. (this is important because you can find the basic stuff there)

So today I’ll teach you, how to detect touched GameObjects. My code will be fully commented, but I have to write a few lines about it.

There are several phases of a touch:

Began

Ended

Cancelled

Stationary

Moved

I think these names speak for them self. So if you press the screen then that’s a beginning of the touch. When you release it, that’s when it’s ended. etc…

So we would like to know the gameobject what we touched on the screen. We can do it by raycasting. Raycasting only detects gameobjects is there is a collider attached to them.

For a single touch environment where we only need to detect one touch:

#if UNITY_ANDROID || UNITY_IOS || UNITY_WP8 void Update(){ //We check if there are any touches on the screen if (Input.touchCount > 0) { //We get the first touch (touches are stored in an array) Touch touch = Input.touches[0]; //This is how we can get the position of our touch Vector3 touchPosition = Camera.main.ScreenToWorldPoint(touch.position); //Now we have to raycast to see if it is hitting something //Raycast starts from the touched position, and it doesn't need a direction (that's why it's Vector2.zero) RaycastHit2D hit = Physics2D.Raycast(touchPosition, Vector2.zero); //Checking the raycast if we hit something if(hit.collider != null){ //This is what we used in our previous tutorial //You can play with the touchphases as you like it 🙂 if(touch.phase == TouchPhase.Began){ Debug.Log("Touch BEGAN. Touched gameobject's name: " + hit.collider.name.ToString()); } if(touch.phase == TouchPhase.Ended){ Debug.Log("Touch ENDED. Touched gameobject's name: " + hit.collider.name.ToString()); } } } } #endif

Multi touch:

We need to check every single touch. Touches are stored in an array so with a simple foreach we can modify the single touch code.

#if UNITY_ANDROID || UNITY_IOS || UNITY_WP8 void Update () { if (Input.touchCount > 0) { //Here is the foreach loop. With this we can make it "multi touch" compatible foreach (Touch touch in Input.touches) { Vector3 touchPosition = Camera.main.ScreenToWorldPoint(touch.position); RaycastHit2D hit = Physics2D.Raycast(touchPosition, Vector2.zero); if(hit.collider != null){ if(touch.phase == TouchPhase.Began){ Debug.Log("Touch BEGAN. Touched gameobject's name: " + hit.collider.name.ToString()); } if(touch.phase == TouchPhase.Ended){ Debug.Log("Touch ENDED. Touched gameobject's name: " + hit.collider.name.ToString()); } } } } } #endif

I hope you like this tutorial. If you have any trouble or you have any question just leave a comment and I’ll be happy to help. 🙂