Monday 1 May 2017

How to detect touch on any gameObject in Unity

Background

You can have multiple GameObjects on your scene in Unity. How can we determine if user has touched a particular element. We will see how in this post. We will use Physics2D.Raycast() for this.

Code 

You can do something like following -

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

public class GameInputs : MonoBehaviour {

    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {

        //We check if we have one or more touch happening.
        //We also check if the first touches phase is Ended (that the finger was lifted)
        if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Ended) {
            //We transform the touch position into word space from screen space and store it.
            Vector3 touchPosWorld = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            Vector2 touchPosWorld2D = new Vector2(touchPosWorld.x, touchPosWorld.y);
            //Debug.Log("Touched " + touchPosWorld.x + "" +  touchPosWorld.y);
            //We now raycast with this information. If we have hit something we can process it.
            RaycastHit2D hitInformation = Physics2D.Raycast (touchPosWorld2D, Camera.main.transform.forward);
            if (hitInformation.collider != null) {
                //We should have hit something with a 2D Physics collider!
                GameObject touchedObject = hitInformation.transform.gameObject;
                //touchedObject should be the object someone touched.
                Debug.Log("Touched " + touchedObject.transform.name);
                switch (touchedObject.tag) {
                case "StartGameButton":
                    Debug.Log("Touched StartGameButton " + touchedObject.transform.name);
                    break;
                case "LikeButton":
                    Debug.Log("Touched LikeButton " + touchedObject.transform.name);
                    Application.OpenURL("https://play.google.com/store/apps/details?id=com.osfg.ringtonesetter.main");
                    Application.OpenURL("market://details?id=com.osfg.ringtonesetter.main"); 
                    break;
                case "SettingsButton":
                    Debug.Log ("Touched SettingsButton " + touchedObject.transform.name);
                    Application.LoadLevel ("Settings");
                    break;
                }
            }

        }
    }
}

Explanation and setup

As you can see we are using Physics2D.Raycast() to case a ray from camera to point of touch and then detecting a collision. Finally if we have collision information we check the tag associated with it to check out element of interest.
  1. Make sure for each such elements you add a collider component like 2D Box collider. Only then collision will work.
  2. Make sure you tag each elements correctly and use it to get your object when touched.


Other Notes :

  1. You can create a prefab of background and use it in all your app screens to be consistent. That way changes made in prefab will be applicable to all instances of it.
  2. If your scene is not getting correctly displayed you can correct it by clicking on "Main Camera" and then Game Object -> Align view to selected

How to center a GUI button in Unity

Background

In previous post we saw how to setup unity for creating Android application. In this post we will see how to create a simple GUI button in a scene and put in in the center of your screen.

How to center a GUI button in Unity

Create or load an existing project. Next create a C# script and attach it to any of the objects on the screens. You can attach it to the camera as well. I am doing the same for this post. Now open this script in Monodevelop.


I have three different scenes in my project -
  1. GameStart
  2. GamePlay
  3. GameEnd
Since this post only deals with centering of a GUI button I will not bore you with other scene details. Well just concentrate on GameStart scene which will have a GUI button in the center of the screen that says - "Start Game".

So create a C# script called  GameStart.cs (you can name it anything you want)., attach it to camera in GameStart scene and open it in Monodevelop of editing.

Paste following code in it -

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

public class GameStart : MonoBehaviour {

    public void OnGUI(){
        if(GUI.Button(new Rect(Screen.width/2-50,Screen.height/2-25,100,50),"Start Game!")) {
            Debug.Log("Start Button clicked");
            Application.LoadLevel ("GamePlay");
        }
    }
}



Now lets understand whats going on. OnGUI() is the method that is called by Unity engine to render GUI components. We are going to add our button in this method.

Next we create a button using method GUI.Button() which takes its x position, y position, it's width and it's height as Rect object which is 1st argument to Button. 2nd argument is the text itself that will be shown on the button UI. We are showing "Start Game" there. What goes inside the wrapped if will get executed when the button is clicked. We are simply logging the click event and loading scene2 i.e GamePlay scene.

Point to note here is the x,y coordinates and the height/width of the Button. Notice how we have used Screen.width and Screen.height values here, then divided it by 2 to get mid and then adjusted the coordinates as per the actual width and height of the button we want.

It would look like below -



Now start up console. You can do so using
  • Windows -> Console
Now click on Start Game! button and notice console output.

 It will also load scene 2 but ignore that for now. Monodevelop code looks like below -




Related Links

t> UA-39527780-1 back to top