Introduction: How to Make an Android App Using Unity

Before I start, I should probably mention that this will be a lengthy tutorial. So prepare yourselves. By the end of this tutorial, you'll be able to take on the world (in a figurative sense.)

Approximately two years ago, I delved into new territory and took a course in Game Design. I'd never attempted to make a game properly before this. I tried to get into programming but couldn't commit to it. I wrote maybe a couple of very basic command-line programs that were a few lines long and then just gave up as I couldn't get my head around it.

So when I started my course, I was not used to it. Over the two years, I learned a lot and made excellent progress and even designed and programmed a few games and apps, 2 of which are for Android.

Going into a bit more detail. As this was a course, I was required to learn everything related to game design and development. I learnt how to generate game ideas, how to write a story for the game, how to conceptualise characters (I haven't designed any characters), how to create a game design document (which is very useful, it doesn't have to be highly detailed if you're an indie developer), how to use Unity Game Engine to create the game, how to test the game correctly and how to build a game for different platforms.

Step 1: Table of Contents

  1. Table Of Contents
  2. Things You Need To Know Before You Begin
  3. How To Set Up Unity & Android Studio
  4. Setting Up Project & Creating Particle Prefabs
  5. Creating & Adding Effects Script
  6. Creating & Adding Touch Controls
  7. Testing
  8. Creating Main Menu & HUD
  9. Organising Hierarchy
  10. Conclusion

Step 2: Things You Need to Know Before You Begin

Many people might think that game design/development is complicated and requires much prior knowledge to make one. However, this is far from the truth. Using a game engine will drastically reduce the learning curve and allow you to focus more on making the game fun. There are a variety of different game engines out there; the most popular options are:

  • Unity
  • Unreal Engine
  • CryEngine

Unity and Unreal Engine are more popular than CryEngine. This is because they are aimed toward indie developers and AAA developers, as opposed to CryEngine, which is aimed only at AAA developers. The difference between Indie and AAA:

Indies are comprised of small teams, usually 1-20 people, and they don’t have significant funds, etc.

Some examples of Indie devs:

  • Coffee Stain Studios
  • Halfbrick Studios
  • Mojang
  • Ndmeic Creations

AAAs are comprised of much larger teams and have a lot of experience in the industry, along with a lot of funds. Some examples:

  • EA
  • Ubisoft
  • Gameloft
  • Treyarch
  • Activision

A game engine is a program designed to simplify game design/development. Instead of coding every single aspect of the game yourself, you can just script the behaviour using a game engine. This is made possible by the fact that game engines do a lot of the work for you; things such as physics, lighting, rendering etc., are all done for you. All you have to do is create the game objects (these are just containers with different elements attached), set up the order and layout, assign the relevant properties to the game objects and script the behaviour.

Some game engines allow you to create a whole game without any coding required at all; the most popular one is Unreal Engine. It features a Blueprints system, which utilises a node-based structure (essentially just a system that uses boxes and arrows. These boxes and arrows are linked if they are part of the same function). Let’s say you wanted to intercept keyboard input (this means telling the program to look out for a key pressed on the keyboard) and then make the player move as long as that specific key is held down. You would create a base node, which would contain the necessary sub-functions. In that base node, you would declare the key you wanted to use and then generate another node telling the game what to do. The base node would be a box containing the function for pressing the key.

In this case, the second node would cause the player to move in a direction (forward, for example) as long as the “W” key is held down. The second node would be another box linked to the first box. This is extremely useful, not just for designers but also for programmers, as it allows them to create prototypes rapidly. Unity does also have this feature, which is known as visual scripting. However, it takes the form of an asset that you must buy.

Unity is better for beginners looking to make games as it teaches you how to script. Unreal Engine is much more advanced, even though it features visual scripting. Which means there is a more significant learning curve.

Step 3: How to Set Up Unity & Android Studio

So now you know a bit more about game engines and how they function. This tutorial will be using Unity 5.3.5, which is the latest version at this time. I will be teaching you how to create an aesthetically pleasing Android app. This tutorial assumes that you have a basic understanding of using Unity. If you’re a complete beginner and you want to follow this tutorial, then please visit this link to become acquainted with the basics of Unity: http://pixelnest.io/tutorials/2d-game-unity/

Ensure you always have the latest Unity version, as they contain bug fixes and improvements. You could potentially run into errors if you have an older version of Unity. These errors can usually be fixed by updating. I should also mention that building for any mobile platform requires the respective SDK installed on your computer (for Android, you need Android Studio. For iOS, you need a Mac with Xcode installed.) To download Android Studio, please follow this link and set it up using the instructions provided on the website: https://developer.android.com/studio/index.html

Once installed, you will need to install the drivers for your phone by opening Android Studio, clicking Configure > SDK Manager, and then clicking Launch Standalone SDK Manager. A new window will open up, scroll to the bottom and ensure that the Google USB and Web Drivers are selected. You can leave the other components chosen by default. Then click on Install Packages in the bottom right and wait for it to install. Once that is done, go to the Settings app on your phone > About/About Phone > Software Information and locate the “Build Number” header. It should be a collection of numbers with decimals and “release-keys” appended to the end. Tap the “Build Number” multiple times until it says “Congratulations, you are now a developer” or something similar. Then go back to your Main Settings page and locate “Developer Options”. Click on it and find the “USB Debugging” checkbox. Ensure this is ticked. Then plug your phone into your computer and ensure “USB Debugging Enabled” or something similar is showing in the Notification Bar; you will most likely need to expand the Bar to see the message.

Regardless of whether you want to install the drivers for your phone to use it in Unity, you will need to have Android Studio installed, as, without it, you can’t build the app for your phone. If setting up the drivers is too tedious, follow the alternative options in the Testing Section of this tutorial. Once you have installed Android Studio and set up USB Debugging, you can come back and follow this tutorial.

This tutorial was based on another tutorial; I’ll provide the link if you want to check it out. http://pixelnest.io/tutorials/unity-touch-controls...

My tutorial covers more than the original (Menu, HUD, and Testing). The programming language I will be using for this tutorial is C#. Unity also supports JavaScript; however, C# has more advanced features, albeit it is slightly harder to learn. You are free to convert the C# code into JS if you already know JS, but unfortunately, I won’t be able to account for any language-specific errors should you choose to use it. I will also teach you some tips and tricks I have learnt while making games. Let’s begin.

Step 4: Setting Up Project & Creating Particle Prefabs

Setting up Project

Once you have successfully created your project, ensure you have the following folders in your assets folder:

  • Fonts
  • Materials
  • Menu
  • Prefabs
  • Scenes
  • Scripts
  • Textures

These are the only folders you’ll require for this project. However, if you decide to expand on it, you are free to add any other folders as you see fit (sounds, animations etc.)

Once you have created the above folders, go to File > Build Settings. In this window, click on the Android option under the header “Platforms”, then click on “Switch Platform” in the bottom left corner. This will tell Unity that you’re building for Android and will set up the project. You will need Android Studio installed for this to work. Then save the scene by either pressing Ctrl+S or choosing “Save Scene” in the File Menu. Save this scene as “Main Scene” in your “Scenes” folder.

Creating Particle Prefabs

Above is an image of a star with a black background. Save this image into your Textures folder. You will be using it for the Particle System.

Set the Texture Type to Texture by clicking on the image in your Textures folder and selecting the appropriate value in the Inspector, then click Apply. Ensure the “Alpha Is Transparency” box is ticked. This will make the background of the star transparent.

Then create a Particle System and set it up using the values shown in the screenshot above.

Feel free to modify these values if you’d like; they are just guidelines. Playing around with these values will give you a better understanding of how it works.

Ensure that the Texture of the Particle System is set to the Star Texture by expanding the Shader and selecting the Star Texture in the box on the right. Or you could drag and drop the image from your Textures folder into the box. Choose the Mobile/Particle/Alpha Blended Shader by clicking the drop-down box next to Shader, then Mobile > Particles > Alpha Blended. This will tell the particle system to make the background of the Star transparent and will optimise it for Android. Change the name at the top in the Inspector to “Explosion” and do the same in the Hierarchy. Then drag this Explosion Particle System from the Hierarchy to your Prefabs folder in the Project view. This will create a prefab of that Particle System.

Next, we will be creating a Trail Prefab, which will draw a trail as long as you drag your finger on the screen. The trail will disappear after a couple of seconds when you lift your finger.

Create a new Empty Game Object (Right Click in the Hierarchy and select “Create Empty”) and call it Trails or something similar. Then add a Trail Renderer component to it. Set it up using the values provided in the screenshot above.

Create a new Material by clicking on the Materials folder in the project view, then Right Click in the project view and click Create > Material. Name the Material as Trails Material or Trails Mat.

Then click on the Trails Game Object in the Hierarchy and drag and drop the Trails Mat from the Project view to the Inspector window. This will assign the Material to the Trails Game Object. Then drag this Trails Game Object to your Prefabs folder to make it a Prefab.

Finally, we’ll create another Particle System that will be different from the first one. This one will slowly explode outwards, won’t have any gravity, and will slowly fade away. Create another Particle System, and label it Pinch Explosion (we’ll use a pinch gesture to initialise it). Make sure the Star Material is assigned to this Particle System, then make it into a Prefab.

These are all the effects we will be using. Feel free to create more if you like or modify the existing ones; one final thing before we can move on to the programming is to click on the Main Camera in the Hierarchy. Change the Background Colour to either black or another dark colour and change the Size (underneath the Projection drop-down box) from 5 to 10. This will allow you to see more of the background. Look at the final screenshot above if you’re confused.

Step 5: Creating & Adding Effects Script

Creating the Script

Now that we have created all the prefabs, we can move on to the programming. You will have to write quite a bit of code as this is a more advanced tutorial. I actually have a document that explains the basics of programming if you’re interested. This is also another extensive read. I have uploaded it to Dropbox, here is the link:

http://bit.ly/29qhLDx

Create a new C# Script in your Scripts folder (click on Scripts folder, then Right Click in the Project Window > Create > C# Script) and label this Script as “SpecialEffects”. Open it up in your desired IDE (Integrated Development Environment) and write out the code below, word for word. The reason I’m telling you to write it word for word as opposed to copy/pasting it is because typing it will allow you to understand what the code does better. It will also get you in to the practice of checking your code for any errors. Here is the code:

{
 /* Makes this script a private static, meaning this script's functions 
     can't be accessed outside of this script
     and it's values don't ever change unless you specifically tell it to */ 
    private static SpecialEffects instance;
    // These are the prefabs
    public ParticleSystem explosionEffect, pinchExplosionEffect;
    public GameObject trailsPrefab;
    /* This function is activated when the script is first initialised, 
       before the Start function. 
       The Start function requires this script to be enabled but the Awake function runs regardless of whether this script is enabled */ 
    void Awake()
    {
        // Assigning the value of instance to this script
        instance = this;
    }
	// Use this for initialization
	void Start ()
    {
        // Ensuring the prefabs are all activated
        if (explosionEffect == null)
            Debug.LogError("Missing Explosion Effect");
        if (pinchExplosionEffect == null)
            Debug.LogError("Missing Pinch Explosion Effect");
        if (trailsPrefab == null)
            Debug.LogError("Missing Trails Prefab");
	}
    // Explosion Effect
    public static ParticleSystem MakeExplosion(Vector3 position)
    {
        // If this script is disabled, log an error
        if (instance == null)
        {
            Debug.LogError("There is no SpecialEffects Script in the scene");
            return null;
        }
        // Creates the Explosion Effect at the given position
        ParticleSystem effect =
            Instantiate(instance.explosionEffect) as ParticleSystem;
        effect.transform.position = position;
// Destroys the Explosion Effect after Effect has completed        
Destroy(effect.gameObject, effect.duration);

return effect;    
}
    // Pinch Explosion Effect
    public static ParticleSystem MakePinchExplosion(Vector3 position)
    {
        // If this script is disabled, log an error
        if (instance == null)
        {
            Debug.LogError("There is no SpecialEffects Script in the scene");
            return null;
        }
        // Creates a Pinch Explosion at the specified position
        ParticleSystem effect =
            Instantiate(instance.pinchExplosionEffect) as ParticleSystem;
        effect.transform.position = position;

return effect;
 }
    //  Trail Effect
    public static GameObject MakeTrail(Vector3 position)
    {
        // If this script is disabled, log an error
        if (instance == null)
        {
            Debug.LogError("There is no SpecialEffects Script in the scene");
            return null;
        }
//Creates a new trail at the set position
GameObject trail = Instantiate(instance.trailsPrefab) as GameObject;       
trail.transform.position = position;

return trail;
}

Adding the Script to the Scene

See, that wasn’t too hard, was it? Now that we have this script ready, we can add it to the scene. Create a new Empty Game Object, label it as Scripts and drag the Script from your Scripts folder on to the Scripts Game Object.

Now assign the Variables to their respective Prefabs by dragging the Prefab from the Prefabs folder in the Project View to the Scripts properties in the Inspector Window. See the screenshot above for reference.

Step 6: Creating & Adding Touch Controls Script

Creating the Script

Now it’s time to program the touch controls for this app. The primary function of this app is to trigger effects when the screen is touched. The three gestures we will be using will be a tap, a swipe and a pinch to zoom. You can also add more gestures if you wish, but you will have to do that of your own accord.

The effects we trigger will vary based on the type of touch input (tap, swipe, pinch to zoom etc.) This will allow us to ensure that the correct gesture is being recognised.

The method in which we will detect these gestures is using Unity’s “Input” class, which consolidates all the information about every type of Input in to one location. Some examples of other Inputs are keyboard, console controllers or touch.

Unity has a specific sub class called Input.touches and it contains the events for the various types of touches along with their state in a certain frame.

A Touch is a container that holds the information about the various fingers, which we will be looking at while programming the touch controls.

The first type of touch method that we’ll be implementing is a pinch, then the tap, then the swipe. A pinch is when the screen is touched with two fingers and dragged either outwards or inwards. A tap is when the screen is touched for a short amount of time (usually a second). It is similar to clicking a mouse. A swipe is when the screen is touched with one finger and dragged along the screen.

Create new Script in your Scripts folder and label it “TouchControls”. Then type in the following code under the Update function.

using UnityEngine;
using System.Collections.Generic;
public class TouchControls : MonoBehaviour
{
    private Dictionary trails = new Dictionary();
    private Touch pinchFinger1, pinchFinger2;
    private ParticleSystem pinchExplosion;
    // Use this for initialization
    void Start ()
    {
	
    }
	
	// Update is called once per frame
	void Update ()
    {
        // These are the touch controls
        // Uses a loop to search for all of the fingers
        // Controls for Pinch To Zoom, only works with 2 fingers
        // If 2 fingers are on the screen
        if (Input.touchCount == 2)
        {
            // Assign these 2 fingers to their own variables
            var finger1 = Input.GetTouch(0);
            var finger2 = Input.GetTouch(1);
            if (finger1.phase == TouchPhase.Began && finger2.phase == TouchPhase.Began)
            {
                this.pinchFinger1 = finger1;
                this.pinchFinger2 = finger2;
            }
            // When the fingers have moved, update the script to the new location
            if (finger1.phase == TouchPhase.Moved || finger2.phase == TouchPhase.Moved)
            {
                float baseDistance = Vector2.Distance(this.pinchFinger1.position, this.pinchFinger2.position);
                float currentDistance = Vector2.Distance(finger1.position, finger2.position);
                // Purcent
                float currentDistancePurcent = currentDistance / baseDistance;
                // Creates the effect between the fingers if it doesn't currently exist 
                if (pinchExplosion == null)
                {
                    Vector3 finger1Position = Camera.main.ScreenToWorldPoint(this.pinchFinger1.position);
                    Vector3 finger2Position = Camera.main.ScreenToWorldPoint(this.pinchFinger2.position);
                    // Finds the centre between the 2 fingers
                    Vector3 pinchExplosionPosition = Vector3.Lerp(finger1Position, finger2Position, 0.5f);
                    pinchExplosion = SpecialEffects.MakePinchExplosion(pinchExplosionPosition);
                }
                // Takes the base scale and increase or decrease it
                pinchExplosion.transform.localScale = Vector3.one * (currentDistancePurcent * 1.5f);
            }
        }
        else
        {
            // If the pinch has been released
            if (pinchExplosion != null)
            {
                // Create Explosions
                for (int i = 0; i < 10; i++)
                {
                    var explosion = SpecialEffects.MakeExplosion(pinchExplosion.transform.position);
                    explosion.transform.localScale = pinchExplosion.transform.localScale;
                }
                // Destroy Pinch Explosion Effect
                Destroy(pinchExplosion.gameObject);
            }
            // Tap effect 
            // Checks for all fingers
            for (int i = 0; i < Input.touchCount; i++)
            {
                Touch touch = Input.GetTouch(i);
                // A tap is a quick touch and release
                if (touch.phase == TouchPhase.Ended && touch.tapCount == 1)
                {
                    // Touches are screen locations, this converts them in to world locations
                    Vector3 position = Camera.main.ScreenToWorldPoint(touch.position);
                    // Creates the Explosion Effect
                    SpecialEffects.MakeExplosion((position));
                }
                else
                {
                    // Controls for the Swipe Gesture
                    if (touch.phase == TouchPhase.Began)
                    {
                        // Store this new value
                        if (trails.ContainsKey(i) == false)
                        {
                            // Touches are screen locations, this converts them in to world locations
                            Vector3 position = Camera.main.ScreenToWorldPoint(touch.position);
                            // Ensures the trail is visible
                            position.z = 0;
                            // Creates the Trails Effect
                            GameObject trail = SpecialEffects.MakeTrail(position);
                            // If the trail is still enabled
                            if (trail != null)
                            {
                                // Log the trail
                                Debug.Log(trail);
                                // Add some more Trails 
                                trails.Add(i, trail);
                            }
                        }
                    }
                    else if (touch.phase == TouchPhase.Moved)
                    {
                        // Moves the trail
                        if (trails.ContainsKey(i))
                        {
                            // Array for the Trails
                            GameObject trail = trails[i];
                            // Converts touches in to world locations
                            Camera.main.ScreenToWorldPoint(touch.position);
                            Vector3 position = Camera.main.ScreenToWorldPoint(touch.position);
                            // Ensures trail is visible
                            position.z = 0;
                            // Sets position of the trails to position of the finger
                            trail.transform.position = position;
                        }
                    }
                    else if (touch.phase == TouchPhase.Ended)
                    {
                        // Clears all visible trails
                        if (trails.ContainsKey(i))
                        {
                            GameObject trail = trails[i];
                            // Fades trails out
                            Destroy(trail, trail.GetComponent<TrailRenderer>().time);
                            trails.Remove(i);
                        }
                    }
                }
            }
        }
    }
}

For the Tap function, we retrieve the location of all the fingers placed on the screen, whether it’s one finger or four and then we create an Explosion effect when the finger has been taken off the screen, in the position where it was, before the finger was taken off.

For the Drag function, a new variable was created. We need this variable to create the link between a finger and a Trail. What the code does:

If a new touch has been created, create new Trail and link it to the finger by way of the dictionary.

When the finger is moved, as long as the finger has a Trail linked to it, the position of the Trail Game Object is moved along with the finger.

When the finger is lifted off, the trail is destroyed.

For the Pinch function three more new variables were created. These variables stored the first position of the fingers, which we then used calculate the difference between the distance of the fingers. A variable for the Pinch Explosion effect was also created so that we could update and destroy it.

The Pinch function was more complicated, due to the fact that we didn’t want it being mistaken for anything else.

For the Pinch function, if two fingers are detected on the screen, a new Pinch Explosion effect is created in between the two positions. After that, the gesture is declared as a Pinch. If the fingers are moved, the Pinch Explosion Game Object is also moved and scaled along with it.

Once the Pinch Explosion has completed, or if a finger is lifted off the screen, it changes in to the normal Tap Explosion.

Adding the Script to the Scene

Now that the Controls Script is complete, add it to the scene the same way as the previous script or it won’t work.

That’s the main programming done. We will still need to do some more programming for the Menu & HUD, but it will be much less and easier to understand. But, before we get on to the Menu we need to actually test the app to see if it performs as it should.

Step 7: Testing

Testing is crucial when developing any kind of software. Without testing, you wouldn’t know if everything functions as it should.

Ideally, you should be testing as soon as you implement a new feature, however, for the purposes of this tutorial, we’re testing after we’ve implemented most of the features.

There are multiple methods of testing. The most effective one is to build and run the app on an Android phone as you go along. Unity actually allows you to manage this easily, provided you have the correct drivers installed.

Before you can actually build and test the app, you will need to set up a couple of things. Go to Edit > Project Settings > Player. At the top of the Inspector window you will see “Company Name” and “Product Name”. Change these to whatever you wish. Then expand the “Other Settings” tab if it isn’t already and go to “Bundle Identifier”. Change this to com.CompanyNameYouSet.ProductNameYouSet. In my case my company name is U and my product name is Instructables, so my Bundle Identifier is com.U.Instructables. If you don’t change this then you won’t be able to actually build the app for Android.

If you have the Drivers installed, simply go to Build Settings in the File Menu. Then click on “Add Open Scenes”. It should add the “Main Scene” to the list and give it the number “0”. Once that is done, ensure your selected platform is Android and your phone is connected to your computer then click on “Build and Run”. Unity will start to build your app, however, before it can fully complete the build it will require the location of your Android SDK. To find this location, open up Android Studio > Configure Settings > SDK Manager then look at the top for the “Android SDK Location”. This is the location you must point Unity to. Once Unity knows where the SDK is, it will continue to build your app. Once the app has finished building it will automatically run it on your phone. You are then free to play around with the app and enjoy your hard work. Try all the gestures to ensure that they all work.

Another simple method of testing would be to click on “Build” instead of “Build and Run” and then choose a location to save the .apk (Android’s file extension for its apps) to. Once this file has been saved and built, you will need to transfer it to your phone’s storage, and install it manually on your phone. This method is how you will send your app to other people if you so wish.

Another way of testing is through the Unity Editor. By pressing the Play button on the top of the screen in the middle, Unity will build and run your app/game. This saves you from having to use your phone for minor testing. However, if you want to use this method to test your game on Android, you will need to download Unity Remote 4 from the Google Play Store or iOS App Store. The Unity Remote allows you to test your game in Unity, without having to create a full build every time. It saves a lot of time. One thing to mention is that it does reduce the quality of the graphics on your phone. But this is necessary. It still does a good job of showing you how your app/game will look on your phone. If you’re building for PC (Windows) then you can test the game in the editor without any extra tools. Be sure to exit the Play mode in Unity after you have tested your game as any changes made to any components are reverted when you exit the Play mode.

These methods are the most effective when it comes to testing your game as you can actually see if your code functions the way it should. There are however, other methods that you can also use, these methods are for Microsoft Visual Studio, which is the IDE that I use, but they should be synonymous with other IDEs too.

One method is breakpoints. Let’s say you write some code, then run in to an error. You don’t know exactly where your code is going wrong, but you have a general idea. So you would add breakpoints above, below and on the faulty code. The breakpoints will stop the program when it reaches the breakpoint and give you information about the program up until that breakpoint.

To create a breakpoint, find the line where you think your code is going wrong and click on the first margin to the left. It should be a lighter colour than the main page. A red dot should appear and if you hover over the red dot, it will tell you the location of the breakpoint. See the screenshot for reference.

In the screenshot, I have used the “if (explosionEffect == null” line as the error. Once you have the breakpoint, still in Visual Studio, click Debug > Start Debugging or press F5 on the keyboard. This will run the program inside Unity and link it to VS and on the bottom of the VS window a red bar will appear saying “Ready”.

Now go to Unity and click on the Play Icon. This will run the app/game up until the breakpoint, at which point it will return you to the VS window with information about how the program runs up until the breakpoint. If your game/app runs fine up until the breakpoint, then that line isn’t the one with the error. If, however, your program throws an error before the breakpoint or doesn’t run at all, then it could be that line, or the lines above it. In order to find the erroneous line, you will need to keep adding breakpoints until you have located it. The quickest method is to add multiple breakpoints at a time instead of one. This is a very good way of testing and allows you to be more precise.

Once you have completed your testing, either press Shift + F5 to end debugging in VS or go back to the Debug menu and click “Stop Debugging”. This will then stop the Debug and allow the Unity project to play normally.

When testing, ensure that you use a combination of these methods as opposed to just one as it will allow you to locate exactly where you have gone wrong.

Also be careful with spelling and syntax, programming languages can be rather unforgiving, and C# is one of these languages. If you spell something wrong, you will get an error, and it will be challenging to locate this error as neither VS nor Unity account for spelling mistakes. I have spent hours trying to fix a bug, only to find out that I spelt a function or variable wrong. Checking your spelling and syntax as you go along is a good habit to get in to as it will save you hours in debugging. If you get to the point where you’ve quadruple checked your code and you still can’t figure out what’s wrong, get someone else to look at your code. Ideally you’d want another programmer or someone who at least has knowledge of programming, but if you don’t have anyone who knows programming then get anyone who’s with you at the time to look at it. Tell them to look specifically for spelling mistakes as they might be able to pick them out when you can’t.

Try not to get too frustrated if you make a spelling mistake and it takes you ages to find it. It happens to everyone. It’s one of the joys of being a programmer.

Now that we have covered testing, we can move on to making the Menu & HUD.

Step 8: Creating the Main Menu & HUD

Creating a Menu/HUD for your app is actually rather crucial. The Main Menu gives the player information about your app and usually allows them to control certain aspects of the app. For this tutorial, we will not be learning how to program the Menu so that the player can change the settings because there actually isn’t anything for the player to change (there’s no sound, music etc.) I am contemplating adding some sound effects and possibly music, but those will come in a later tutorial. The Main Menu we will be creating will be rather basic but still aesthetically pleasing. We will have a Title & three buttons (Play, Help & Exit.) The Play button will just take you to the Main Scene, the Help button will take you to a Panel with the Help File on it and the Exit button will simply quit the game. I’ll show you two ways to implement the Exit button, the first method will be a bit simpler.

You can use any font, background image etc. that you want, provided it fits the theme of the game. Also ensure that your assets for your game are copyright free or can be used commercially if you plan to release it on an app store otherwise you could run in to some legal issues. For this tutorial, I will be using this image of the Galactic Centre Region:

http://bit.ly/29eP2jB

And these fonts:

http://www.dafont.com/fineliner-script.font

http://www.dafont.com/post-it-penscript.font

The fonts are attached to the bottom of this step and the image is at the top if you want to use these assets for your app.

Once you have downloaded the fonts and images you want to use, import them in to your Unity project in their respective folders (Fonts go in the Fonts folder and the Image goes in the Menu Folder.)

Creating the Menu

In order to create the Menu we need to create a new Scene. Either press Ctrl + N or go to File > New Scene. Save it as Menu or Main Menu.

Now that we have our scene, we need to add a Canvas. This Canvas allows us to use all of the UI features that we require. Think of it as an overlay that is always the exact size of your screen.

To create a Canvas right click in the Hierarchy > UI > Canvas. In the Inspector window of the Canvas, ensure the Render Mode is set to Screen Space – Overlay and tick the Pixel Perfect option. Underneath the Canvas Scaler component, change the scale mode from Constant Pixel Size to Scale With Screen Size. This allow all the components of the Canvas to scale up or down if the screen resolution increases or decreases. Change the Reference Resolution to the Resolution of your phone screen in Landscape View (mine is 1920 x 1080) and change the Match value from 0 to 0.5. This will ensure that the components are scaled equally in Width and Height.

Now you need to change your Game View to match the Reference Resolution of your Canvas. To do this, click on the Game tab at the top, it should have an icon of Pacman to the left of it. If you can’t see it go to Window > Game, or press Ctrl + 2. Look to the top left of the Game window and you should see a dropdown box saying Free Aspect. Click on it. At the bottom, there should be a Plus icon, click on that and change the Type from Aspect Ratio to Fixed Resolution. Label it to whatever your phone screen resolution is (mine is 1080p) and change the Width and Height to match your desired Resolution. This will allow you to scale your components so they display correctly on your phone. If you kept it on Free Aspect, it would be difficult to scale your components appropriately.

Create a Panel (same way you created the Canvas, only this time, choose the Panel instead). If your Canvas is already selected then the Panel should automatically become a child of the Canvas.

In Unity, children and parents are extremely important. A child is a sub set of the parent, it inherits certain qualities from the parent. To differentiate between a child and parent: a parent will have an arrow to the left of their name which you can click to show or hide the children.

To create a child, you simply need to either right click on an object in the Hierarchy and then create your child object from the Menu that comes up or you can drag any one object on to another to make it a child of that object. In the screenshot above, I have created an Empty Game Object and dragged it on to the Canvas to make the Empty Game Object a child of the Canvas. This is extremely useful and in some occasions, critical. For example, if you created a panel outside of the Canvas (if the Panel was a parent) and you wanted to scale it to the same size as the Canvas, you would need to find out the dimensions of the Canvas and then manually set the dimensions of the Panel to be the same. However, if the Panel was a Child of the Canvas then you could just scale it using the Anchors (which I will explain in a bit). If you created the Panel to be, by default a child of the Canvas then the Panel would automatically be scaled to the Canvas. There is also the slight issue of any UI elements not being visible unless they are all children of the Canvas. Parents/children are also useful for organising the Hierarchy, which I will also go over soon.

Now that we have this Panel, we can set up the Background Image. Before we do that, we need to name them appropriately, change the name of the Canvas in the Hierarchy to Menu Canvas and change the name of the Panel to Background Image. Now click on the Background Image Panel and look at the Inspector window. There should be an Image (Script) component attached. Look for the Source Image. To change this Image, either drag and drop the downloaded Image from your project window to the box or click on the symbol of a circle with a small dot in the middle. That should open up another window labelled Select Sprite. From this window you can then choose your background. If you can’t see your image make sure the image type is set as a Sprite (2D & UI).

Once you have selected your Background, you will need to increase the Alpha, to do so click on the Color box and at the bottom there will be a slider box labelled A. Drag this all the way to the right until it’s at the end of the white section and its value is set to 255. You can also tint the image a certain colour from this same window if you wish.

To set up the Title, create a Text object as a child of the Background Image. Rename it to Title. Change the colour of the Text to white and ensure that any subsequent Text Game Objects you create are also white. In the Text section, change it from New Text to whatever you want your Title to be (in this case it’s Instructables) and change the font to your preferred font (I’ll be using the Postit-Penscript font). Under the Paragraph header, change the Alignment to whatever you wish, I’ll be centring my text in the Vertical and Horizontal axes. Next, click on Best Fit and change the Max Size to whatever fits your font best. My font is quite thin so I’ll be using 90 as my Max Size. Ensure you click the Best Fit option for every subsequent Text Game Object you create.

Then look to the top right under the Rect Transform header and you should see a box with lines and some text on the top and the left sides of the box. It should say center at the top and middle on the left. Click on this box, hold Alt and Shift and click on the icon above the middle/center icon. Check the screenshot for reference. Now if you close the box it should say center at the top and top on the left and your text should be centred to the top. This is the Anchor and it’s extremely useful when arranging Game Objects. Holding Alt sets the position of the Object to the new Anchor point, and holding Shift sets the pivot. It saves you from having to manually set the locations of the objects.

If you look to the right of the Rect Transform box you should see a bunch of numbers. These are the dimensions and location of the object. The ones you want to focus on are the: Pos X, Pos Y, Width & Height boxes. The Width & Height are self-explanatory. The Pos X moves the object horizontally and the Pos Y moves it vertically. However, these boxes will change based on the Anchor you use. If you use the uniform stretch Anchor, the Pos X & Y will change to Right, Left Top & Down which does the same thing, but it allows you more control. You can either drag along the label of these boxes to move the object, type the numbers in manually, or use the Unity tools to move them. Change the Pos Y from 0 to -10. This will give it 10 pixels of space from the top of the Background Image, making it look a bit cleaner.

Click on Add Component and add a Shadow and Outline. Increase the Alpha of both to 255. This will make it stand out more against the background. Ensure you add a Shadow and Outline component to every subsequent Text Game Object you create.

Now that we have our background it’s time to set up the buttons. Create an Empty Game Object as a child of the Background Image Panel and call it Buttons Layout Manager. In the Inspector window of this Empty Game Object, click on Add Component and search for Vertical Layout Group and add it to the object. This Game Object will keep the buttons’ placement consistent. Change the Anchor to Stretch Uniform (it’s on the bottom right) and change the position and pivot with it. The Buttons Layout Manager should now take up the entire screen. Drag it down from the top until it takes up 3 grid boxes and drag it from the right until it takes up two grid boxes. If you can’t see the grid, look on the top of the Scene window where it says Gizmos. Click on that and then click on Show Grid.

Now create another Text Game Object as a child of the Background Image and set it up the way you want. Label it Start. If you’re using multiple fonts, use your second font for the button and keep the first font for your Titles only. I’ll be using the Fineliner_Script font for my buttons. You can make the buttons any size you want provided they’re clearly visible. A good rule is to make the button size 10 or 20 pixels smaller than the Title, so if the Title is set to size 90, you’d set the button size to 80 or 70. I’ll be setting my button size to 70. Change the Text to Start and set up the alignment to whatever you wish. Add a Button component to it and change the Highlighted and Pressed colours to your preferred colours, ensure the Pressed Colour is darker than the Highlighted one. I’ll be setting my Highlighted to a Light Blue and the Pressed Colour to a Darker Blue. Now add a Shadow and an Outline component to it and increase the Alpha to full.

Duplicate this button twice (by right clicking on the button and selecting Duplicate or clicking on the button and pressing Ctrl + D) so you end up with three buttons in total, call one of them Help and the other Exit. Change the Text of these to reflect their labels. Make them children of the Layout Manger.

Create a Panel, call it Help Panel and set the Source Image to be the same as the Background Image. It should already be the correct size. Increase the Alpha to full. Duplicate the Title and make it a child of the Help Panel. Change the name of the Game Object to Help Panel Title and the Text to Help Panel. It should already be in the correct location.

Duplicate one of the buttons and rename it to Back. Make it a child of the Help Panel then change the Text of the button to Back. Set the anchor, position and pivot to Bottom Left and change the Pos X to 10.

Create another Text Game Object as a child of the Help Panel, label it Help Text Body and set its Anchor to Stretch Uniform. Change the Top box from 0 to 110. Change the Left, Right & Bottom boxes to 10. Set up the Font, use the same font as the Buttons. Change the Max Size to 80. Centre the Text in both axes. Then copy and paste the following text in to the Text box:

This app allows you to create various effects on your phone. Tapping the screen will create an explosion, pinching the screen will create a bigger explosion and dragging the screen will create a trail.

Or create your own help text.

Now go to File > Build Settings > Add Open Scenes. You Menu Scene should now be added. Drag your Menu Scene to the top so that its number is 0 and the Main Scene is 1. If you don’t do this, you won’t be able to actually view your Menu when you build the App, nor will you be able to load the Main Scene when clicking Start.

Now that we have set up the Menu, we can move on to programming it so it actually does something.

Programming the Menu

Create a new Script and call it Menu. Then type in the following code:

using UnityEngine;
// This namespace is required for using any UI components
using UnityEngine.UI;
//  This namespace is required to use the SceneManager
using UnityEngine.SceneManagement;
using System.Collections;
public class Menu : MonoBehaviour
{
    // These are all the buttons
    //-------------------------------
    public Button start;
    public Button help;
    public Button exit;
    public Button back;
    //-------------------------------
    // This is the Help Panel
    public GameObject helpPanel;
    //-------------------------------

// Use this for initialization
    void Start()
    {
        // Disables the panel
        helpPanel.SetActive(false);    
    }
// Update is called once per frame
    void Update()
    {
    }

// Function for Start Button, loads Main Scene 
    public void StartPress()
    {
        SceneManager.LoadScene(1);
    }

// Function for Help Button, enables Help Panel
    public void HelpPress()
    {
        helpPanel.SetActive(true);
    }

// Function for Exit Button, exits the application
    public void ExitPress()
    {
        Application.Quit();
    }

// Function for Back Button, disables Help Panel
    public void BackPress()
    {
        helpPanel.SetActive(false);
    }
}

Drag this Script on to the Menu Canvas then scroll down to the bottom in then Inspector Window. You should have:

Start

Help

Exit

Back

Help Panel

Drag the relevant Game Objects to their respective fields. See the screenshot above if you’re unsure.

Now Ctrl click on the Start, Help, Exit and Back buttons and scroll down to the Button (Script) component. At the bottom of this component will be an empty list that says On Click (). Click the Plus symbol. Now drag the Menu Canvas Game Object in to the field that says None (Object). The No Function drop down box should now be active.

Click on the Start button, then click on the No Function drop down and go to the bottom of the list where it says Menu. Then click on StartPress (). It should now say Menu. StartPress in the dropdown box. Do the same for the Help, Exit and Back buttons but make sure you select the correct Press function for them. The Help button should have HelpPress, the Exit button ExitPress and the Back button BackPress. Now click the Play icon and test it out, click on the Help button and see if the Help Panel Loads. Clicking the Exit button won’t actually do anything unless you’ve built the App for Android. You’ll have to test the Exit button on your phone. Clicking the Play button should take you to the Main Scene.

Now might be a good time to test your app on your phone so build and run it and ensure your Menu is fully functional.

As I mentioned before there are multiple methods of creating the Exit Function. I just showed you the easiest way. This is the second method.

Create another Panel as a child of the Background Image and call it Exit Panel. Set the Background Colour to match the Background so it appears to blend in (I chose a Dark Blue) and set the Top and Bottom to 450 and the Right and Left to 760. This will centre the box on the screen.

Duplicate the Title and make it a child of the Exit Panel. Decrease the size of the text a bit so it is visible but doesn't take up too much room. Ensure its centred to the top.

Duplicate the Play button twice, make both of the duplicates children of the Exit Panel and change the Anchor, Position & Pivot of one of the buttons to Bottom Left. Change the other one to Bottom Right.

Change the name of the button on the Bottom Right to Yes and do the same with the text. Change the Bottom Left one to No (name and text) .

Open up your Menu Script and add 2 buttons under the back button and a GameObject under the Help Panel using the code below:

public Button yes;
public Button no ;
public GameObject exitPanel;

Add the following code in the Start Function, under the helpPanel.SetActive (false); line:

exitPanel.SetActive(false);

Change the ExitPress Function from

 Application.Quit(); 

to

exitPanel.SetActive(true);

Then scroll all the way to the bottom of the script and under the BackPress() Function add the following code:

public void YesPress()  
       {
        Application.Quit();
       }
public void NoPress()
    {
        exitPanel.SetActive(false);
    }

Finally, go back to Unity, click on the Yes button and change its Function from StartPress () to YesPress () and change the No button to NoPress(). Also ensure you assign the new public variables in the Menu Canvas script (click on Menu Canvas and drag buttons and Panel to their respective fields). Now press Play and test the Exit button, it should load the Exit Panel and close it when you press the No button. As you can see, this method is slightly longer but offers protection in case the player accidentally clicks the Exit button. Feel free to use which ever method you choose.

Now we move on to the final step, creating the HUD, which is extremely basic and consists of one button. I might add another tutorial covering a more extensive HUD (with a health slider, a score counter and an actual pause menu) but for now, this will suffice.

Creating & programming the HUD

Go back to your Main Scene and create a new Canvas. Label it HUD Canvas & set it up the same way as the Main Menu Canvas.

Add a Text Game Object as a child of the Canvas, call it Back To Main Menu and set up the fonts, size and alignment to your liking. Alternatively, you could make one of the Main Menu Buttons a Prefab, then just drag it on to your Canvas. Once you’ve set the button up, change its Anchor, position and pivot to the bottom left. Create a new Script called HUD and type in the following code:

using UnityEngine;
// This namespace is required for using any UI components
using UnityEngine.UI;
//  This namespace is required to use the SceneManager
using UnityEngine.SceneManagement;
using System.Collections;

public class HUD : MonoBehaviour
{   
// Button
public Button backToMainMenu;

// Use this for initialization
    void Start()
    { 
   }                        


// Update is called once per frame
    void Update()
    {    

   }    

// Function for BackToMainMenu Button, loads the Menu Scene
  public void BackToMainMenuPress()    
    {
        SceneManager.LoadScene(0);
    }
}

Drag this script on to the HUD Canvas, set up the Script the same way as the Main Menu (by dragging the Back To Main Menu Game Object in the Back To Main Menu field). Then set up the button by dragging the HUD Canvas in to the On Click () field. Choose the BackToMainMenuPress function and test the button by clicking the Play icon and seeing if it takes you back to the Main Menu.

Step 9: Organising Hierarchy

Remember how I said creating Empty Game Objects will help you organise the Hierarchy? Well, you've already been doing that by using children and parents.

However, the Main Scene is a bit unorganised still. Go back to the Main Scene and create an Empty Game Object labelled as Effects. Drag all the Explosions and the Trails Game Objects to this Effects script. Then drag this Effects Game Object underneath the Scripts. The Main Camera & EventSystem can stay as where they are.

Use this system to organise any project you create. Anything of the same type can go under its own Empty Game Object (e.g. Multiple enemies can be children of an Enemies Game Object, multiple Cameras - Cameras Game Object and so on.) This will keep your Hierarchy looking tidy and will prevent yourself from getting confused if you create a lot of Game Objects

Step 10: Conclusion

Phew. That was quite the journey. But we've finally reached the end (you're all probably glad of that.) But now you have a fully functional app that you can show off to your friends and improve upon. You should be proud, as previously mentioned, this was a more advanced tutorial. So take a moment and just enjoy your creation.

I hope this tutorial was a help. If you get stuck on anything, a good habit to get in to is searching Google for your error, then typing in Unity after it. Because Unity is so widely used, there is a lot of documentation available and there will most likely be at least one person who has had the same issue as you.

If you’re not sure about any of the programming functions (void Update, void Start, public void etc.) then search for the function along with unity c# and check the official Unity documentation.

If you can't find an answer to your issues, you can leave a comment and i'll do my best to help you resolve the error.

If there is something you think I could add or if you want to learn how to program an actual game, feel free to leave a comment.

Thanks for taking the time to read this tutorial. Until next time!

Beyond the Comfort Zone Contest

Participated in the
Beyond the Comfort Zone Contest