Thursday, January 17, 2019

Introduction to Mobile Development with Unity

Two things were introduced in 2008 almost at the same time. The iOS and Google Play Store opened up the world of mobile gaming. This new world introduced a new way to play games, all on your smartphone. Since then, it has only gotten easier to create your own apps and release them on a store for all to download and play instantly. It should come as no surprise then that Unity can be used to easily create your own mobile projects. Whether you intend to make a game for yourself or for the world, for iOS or Android, you can make that vision come to life with Unity.

But where do you get started? The same place any creator should begin—with the basics. Follow along and you’ll create a basic app using Unity that does three simple tasks. The first objective is to tap on an object to make it change color. Next, a button will be created that the user may tap whenever they wish to lock the game camera in place. Why would you lock the camera? Well, for the final objective you will be rotating the in-game camera using your phone’s gyroscope. That’s right, by moving your phone in real life the camera will move in your game. All these tasks combine to create a simple app that introduces you to the basics of creating a mobile game in Unity.

Setup

Creating the project is like any other Unity project. Being a mobile project does not change this part of the process. After opening Unity, create a new project as shown in Figure 1.

Figure 1: Creating a new project

Next, name this MobileIntro. Make sure the project is a 3D project then choose the Location for the project. Once you’ve done all this, you’re ready to create the project. It should look similar to Figure 2.

Figure 2: Naming and creating the project.

You may wish to start by creating the objects that will be important to this project. Start by creating a cube. This will be the object the user can tap to change its color to a random color. To create this object, click the Create button in the Hierarchy window. Then navigate to 3D Object->Cube to create the cube object as shown in Figure 3.

Figure 3: Creating a cube.

The cube is rather small at the moment, and anyone that’s done virtually anything with a mobile app knows how difficult it is to tap small objects. You’ll want to increase the cube’s size. Click on the Cube object in the Hierarchy. After this, navigate to the Inspector window and find the Transform component. This should be the first component you see at the very top of the Inspector window. Once found, change all variables in the Scale fields to four as shown in Figure 4.

Figure 4: Naming the object and setting the scale.

Next, you’ll create two more objects. The first is simply a manager that will hold the script that makes the project run. The second will be the user interface (UI) that the user can interact with to lock the game’s camera to its current position. Using the same Create menu in the Hierarchy window, create an empty game object and call it GameManager. Then, once again using the Create menu, navigate to UI->Button to create the button that the user will tap to perform the camera locking function. When finished, the Hierarchy should look similar to Figure 5 below.

Figure 5: The current hierarchy.

You may need to adjust the position of the button you just created to get it in exactly the position you want. Select the Button object in the Hierarchy window and go to the Transform component in the Inspector. Set the anchor to the top left part of the screen. Then set Pos X to 50 and Pos Y to -40. Finally, change the Width and Height of the button to 100 as shown in Figure 6.

Figure 6: Setting the anchor, position, width, and height.

Next, you will want to change the text of the button to say LOCK. In the Hierarchy window, click the arrow next to the Button object as shown in Figure 7.

Figure 7: Opening the child objects.

The button’s Text object will appear. Select it and navigate to the Text component in the Inspector window. You’ll then need to change the text to say LOCK, then adjust the size of the text using Font Size. When finished, the component should look like Figure 8 below.

Figure 8: Setting the text and font size.

With this completed, all the objects needed for the project are in place, but it’s not quite time to write code yet. As this is intended to be a mobile project, you will need to perform a few actions to make the program run on your mobile device. From the top menu select File->Build Settings as shown in Figure 9.

Figure 9: Opening the build settings.

This opens up the Build Settings dialog which shows you the many platforms where you could run an app created in Unity. For each platform, however, different modules will need to be installed. Figure 10 shows the dialog and the message you’ll see about installing the module for Android development.

Figure 10: The Build Settings without having the necessary modules installed.

This is where you would go to build your project to be run on whichever device you choose. In addition, you can navigate to the player settings and change some properties of your build such as the image your application will use. Depending on how you installed Unity you may also need to install the Android or iOS modules for your copy of Unity. You can use the same Unity installer you used to install Unity onto your machine to do this. Just be sure to only select the Android and/or the iOS module for installation.

You may also need to download an SDK for your project to work. This example will be looking at how to install the Android SDK in particular. This can be accomplished either through command line tools or the Android Studio application. Instructions for both methods can be found in Unity’s documentation, found here.

If you already have the above completed, then you’ll need to let Unity know that this is a mobile project. Once again, the example figures will show selecting Android devices as the platform of choice, but you should just as easily be able to use this project on an iOS device. Select the appropriate mobile device for you, then near the bottom of the Build Settings window you will need to click Switch Platform as shown in Figure 11.

Figure 11: Switching platforms.

Once this is done, Unity will rebuild the project and set the target platform to your choice. You’ll see the Unity logo will be next to the platform you selected once the process is complete. Now you’ll need to change a few of the player settings for your project. To the immediate right of the Switch Platform button (now grayed out), click Player Settings shown in Figure 12.

Figure 12: Platform selected. Now on to player settings.

The Inspector window will change showing which player settings you can change for your project. You can do a lot here such as change the app icon or API settings. For this project you will start by changing the orientation of the app. Click Resolution and Presentation, then find the Orientation settings. This project will assume you set the orientation to Landscape Right. Figure 13 shows the settings.

Figure 13: Setting your app’s default orientation.

After this, search for Other Settings. In order to test your project on your phone later, you will need to set up a package name for the project. Under Other Settings you will need to locate the Package Name field. The required format for this package name is com.CompanyName.PackageName. Leave the com part of the name and change the CompanyName and PackageName. It can be set to whatever you wish, but the example below in Figure 14 will simply use com.mycompany.mobileintro as the package name for the project.

Figure 14: Creating a package name for apk file.

Your project’s mobile specific settings have now been configured, and it is time to write the project’s code. Right click in the Assets window and select Create->C# Script as shown in Figure 15.

Figure 15: Creating a C# script.

Name this script PlayScript. Once you’re done, the Assets window should look similar to Figure 16.

Figure 16: The Assets window with PlayScript

Double click the script to open it up in Visual Studio.

The Code

Thankfully, no additional using statements are needed to make this project. The line using UnityEngine should already be in the code upon creation. In addition, you’ll need to add using UnityEngine.UI in order to change the text of the UI button. Finally, you’ll need to declare some variables that will relate to three objects in the project. These objects are the in-game camera, the text in the button, and the cube you created.

public GameObject mainCamera;
public MeshRenderer cubeRender;
public Text buttonText;

After this, a few private variables will be declared. One of them is of the type Gyroscope. As you may have guessed, this has to do with your phone’s internal gyroscope that will be used to move the in-game camera. The next variable, called rotMultiplier, is used to increase how much the camera moves when you rotate your phone. By default, it’s not going to move very far. With this variable you can increase the amount the camera moves whenever the gyroscope detects rotation. In this example the value of rotMultiplier is fifty, but you may need to adjust this number in your own project. Finally, a boolean is created that will tell the project whether to lock the camera or not.

private Gyroscope gyro;
private float rotMultiplier = 50;
private bool lockCam = false;

Now, you move on to the Start function. Whenever the game starts, there will be a quick check to see if the phone you’re using has a gyroscope. Most mobile devices these days have gyroscopes, so why even have the check? This is primarily done to enable the gyroscope functionality for Unity. If for some reason, a mobile device lacks a gyroscope, this could prevent the project from crashing. In that event, you would most likely desire to add an else statement after the if statement and perform anything you wish the project to do in the event that the gyroscope is unavailable. However, this example will assume that your device has a gyroscope, and that no further code is needed. In the interest of good coding habits, the if statement will be used in this example.

if (SystemInfo.supportsGyroscope)
{
        gyro = Input.gyro;
        gyro.enabled = true;
}

The Start function is complete and the code should look similar to Figure 17.

Figure 17: Variable declarations and Start function.

Next, you’ll need to move on to the Update function. Here you will code in the functionality to detect when the cube has been tapped on as well as the camera rotation. The code that catches when the cube has been tapped is as follows:

if (Input.GetMouseButtonDown(0))
{
        Ray ray = mainCamera.GetComponent<Camera>().ScreenPointToRay(
                 new Vector3(Input.GetTouch(0).position.x, 
                 Input.GetTouch(0).position.y, 0));
        RaycastHit raycastHit;
        if (Physics.Raycast(ray, out raycastHit))
        {
                float r, g, b;
                r = Random.Range(0.0f, 1.0f);
                g = Random.Range(0.0f, 1.0f);
                b = Random.Range(0.0f, 1.0f);
                cubeRender.material.color = new Color(r, g, b);
        }
}

That’s curious. Why are you looking for mouse input? Here’s a handy little tip about Unity. You can use some of the same code that you would use for both games that run on a desktop computer as well as games that run on mobile devices. While you could specifically search for a tap of the screen, you may find it easier to simply look for a mouse click. Plus, if you aim to make a project that can work on both PC and mobile, that’s less code to change for each version. This can also be helpful when testing the program on a desktop computer before performing further testing on mobile.

You check to see if a mouse click has occurred. Once you do that, a raycast is created at the point where the mouse cursor was located at the time. A raycast can be thought of as an arrow being shot forward. If it hits something, the program can then gain information on what was hit and even change the object in question upon impact. A good example of this lies in nearly every first-person shooter game. Whenever you fire a gun, you’re not really shooting a bullet out of a gun. Rather, the game is firing a raycast from the gun. Depending on what it hits, a certain action will occur whether that be damaging an enemy or leaving a hole in the wall.

In this case, whenever a raycast hits your cube, the cube will get a new random color applied to it. After getting three random numbers representing red, green, and blue, you get the color variable from cubeRender and assign the new color. After these, you create the code that controls the camera movement. These next two lines of code are fairly simple. If the lockCam variable is false, then rotate the camera based on the inputs from the gyroscope.

if (lockCam == false)
   mainCamera.transform.rotation = 
       Quaternion.Euler(
            gyro.attitude.x * rotMultiplier, 
            gyro.attitude.y * rotMultiplier, 0);

With this code entered into the Update function, you can now move on. The code should look like Figure 18.

Figure 18: The Update function.

Before exiting Visual Studio, there’s one last function to be created. This function, called LockCamera, will be put to use in the UI button you made earlier. Whenever you tap that button, this function will be called. All it does is set lockCam to true or false and changes the text in your button. Placed underneath the Update function, the code looks like this:

public void LockButton()
{
        if (lockCam == false)
        {
                lockCam = true;
                buttonText.text = "UNLOCK";
        }
        else
        {
                lockCam = false;
                buttonText.text = "LOCK";
        } 
}

And with that out of the way, the code for this project is complete. Save your work and head back to the Unity editor to finish the project.

Completing the Project

Remember the GameManager object from before? You’ll attach your freshly made script to this object. With GameManager selected in the Hierarchy, click and drag PlayScript from the assets window into the Inspector as shown in Figure 19.

Figure 19: Attaching PlayScript to the GameManager

Next, you’ll need to fill in the Main Camera and Cube Render fields. In the Hierarchy, select the Main Camera object and drag it into the Main Camera field. Likewise, drag Cube into Cube Render. Figure 20 shows how this looks.

Figure 20: Setting the Main Camera, Button Text, and Cube Render variables.

Next, locate the Button object in the Hierarchy. After selecting it, find the On Click event list in the Inspector as shown in Figure 21.

Figure 21: List of On Click events, currently empty.

Click the + icon to add a new On Click event to your button shown in Figure 22.

Figure 22: Adding an On Click event.

After this you will need to click and drag GameManager from the Hierarchy into the Object field. Figure 23 shows you what to do.

Figure 23: Setting GameManager as the object to pull code from.

Once this is complete, click the drop down menu that current says No Function. Navigate to PlayScript->LockButton to set the LockButton function to this button’s On Click event as shown in Figure 24.

Figure 24: Setting LockButton as the function to call when your button is tapped.

Two steps remain before you can test your project out properly. The necessary modules and SDK you need for the project have been installed. Unfortunately, the SDK doesn’t do much good if Unity doesn’t know where it is. Go to Edit->Preferences to take care of that as shown in Figure 25.

Figure 25: Accessing Unity Preferences.

This opens the Unity Preferences dialog where you adjust settings such as the colors Unity uses. For this project, you’ll want to navigate to External Tools shown in Figure 26.

Figure 26: Navigating to External Tools.

Scroll down until you find settings for Android. This is where you specify the file path for your SDK as well as the JDK (Java Development Kit) and Android NDK. You can also download the things you need using the convenient Download button. For mobile projects, you’ll at least want the SDK and JDK filled in. After installing everything you need, use the Browse button and find the path to your SDK and JDK as shown in Figure 27.

Figure 27: Specifying a path for the Android SDK and JDK.

There’s another step involved to make this project run on your phone, but it takes place outside of Unity. You’ll need to enable developer mode on your mobile device in order to build the project to your phone. On Android, you simply need to navigate to Settings->About phone->Software Information and then find the Build Number. Tap Build Number multiple times to enable developer mode on your phone. For iOS, the process is a little different. You’ll need Xcode running on your desktop, followed by plugging a USB cable from your phone into the computer. From there, navigate your settings until you find Developer. Finding this means you have developer mode enabled on your phone.

After all the above steps have been completed, your project is now ready, but how do you test this out on your phone? After all, it’s hard to test gyroscope functionality on a desktop computer. You can get around this by navigating to File->Build Settings. Once there, you’ll need to click the Build and Run button near the bottom of the window shown in Figure 28.

Figure 28: Building your project and running it on your mobile device.

This will build your game and then upload it to your phone. From there the program should begin running on your phone. Of course, you will need a USB cable connected from your computer to your mobile device for this method to work. Another window will pop up before the build begins saying you need to save the apk file somewhere on your computer. You may save this file wherever you wish, as it will not affect building the apk to your phone. In addition, it’s possible that a dialogue box with a message about JDK will pop up saying it found an up to date version. Go ahead and click Yes on this dialogue.

Once the build is complete, you should see your project begin to play on your phone. If for some reason it doesn’t play automatically, try searching around your apps and see if MobileIntro is anywhere to be found. Once the game begins, go ahead and rotate the device and notice the in-game camera move with your phone’s movements. If there’s a certain angle you like, you can tap the UI button near the top right to lock the camera in place. Finally, try tapping the cube and watch it change to a random color. Remember when I said that you can look for mouse input when looking for taps on your phone screen? You can see that in action both by tapping the cube and tapping the UI button. The app will look something like Figure 29.

Figure 29: Mobile project in action.

Conclusion

As you can see, creating a mobile project is easier than you might think. If you ever wanted to create another mobile game in the future, some settings you edited here in Unity would carry over into other projects, namely the path to the SDK. In some cases, there isn’t much difference between code for a mobile project and code for a PC project, so controlling different versions of the same app becomes easier too. However, it would have been a little underwhelming if all you did was make code that works on both PC and mobile, so you took advantage of your mobile device’s gyroscope to move the camera in time with your own movements. From here you can build off this example project to create your own mobile experience, whatever that may be.

 

The post Introduction to Mobile Development with Unity appeared first on Simple Talk.



from Simple Talk http://bit.ly/2swfrod
via

No comments:

Post a Comment