Showing posts with label Unity. Show all posts
Showing posts with label Unity. Show all posts

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

Saturday, 29 April 2017

Setting up Unity platform to build android games

Background

This tutorial assumes you have already installed Unity.
You can download Unity from their official site - https://unity3d.com/
In this post we will see how to setup Unity to test android games that you develop.

For details you can visit their site - https://unity3d.com/
and you can also see list of games that are already created with Unity. So lets get started -

Setting up android build setup in Unity

Fire up your Unity. Once it is opened you can create a new project and add a new scene to it. It's like creating project in any IDE. Once Unity is up and running go to 
  • File -> Build Settings
 Then
  1. Select android as the platform
  2. Click Switch platform
  3. Click Add Open scenes - this should add all open scenes in build setting
  4. Finally click on build (This step will generate your android apk file. Skip this step if you are doing 1st time well come to this in a moment. Before this we need to have some more configurations.)


 Also you can see Player setting right besides switch platforms. Click this to open a new section of player settings. Here you will see settings that are specific to your android app. If you are developed android apps before then you would know it requires app/bundle id, app icon of different resolutions, app name, api version to build your app, certificate to sign your app for production build etc. all of this you can configure in this section.




 Next you need to tell Unity location of your Android SDK and JDK.  For this go to
  • Unity -> preferences.
This path will be different based on your operating System. For me it's Mac so preferences are in Unity -> Preferences. If you have windows it can be in File -> Preferences.

Once preferences window is opened go to External tools and provide path of your Android SDK and JDK as shown in screenshot below -



 After this your unity is all setup to create and run your android app. Lets see how we can test this setup.

Testing remote android apps

For testing Unity has provided an android app that you need to install on your android device. Before that make sure -
  • Your device has developer mode enabled and have enabled USB debugging
  • It is connected to your machine running Unity with USb cable.
Then you can install unity remote on your device -

Latest one when I am writing this post is unity remote 5. Check accordingly.

Once you have installed it go to Unity on your machine . Now go to
  • Edit -> Project Settings -> Editor
and select Any android device as device.



 That's it. You can just play and you can see your scene running in android unity remote app.

Following are screenshots in playmode from my laptop and android device running unity remote -






Enjoy :)

Related Links

t> UA-39527780-1 back to top