Udemy logo


By Ben Tristem for Unity

Interested in more than a beginner’s guide? Check out Ben’s full Unity course.

Note: This post is part of our “Getting Started” series of free text tutorials on some of our most popular course topics.

To jump to a specific section, click the table of contents below: 


Is Unity for Me?

Is Unity Just for Making Games?

How to Use This Guide

How to Set Up Unity

About Unity Versions

Downloading and Installing

Creating a New Project

Dive Into C-Sharp (C#)

Why We’re Coding First

Writing Your First Script

C# Syntax Basics

Basic Game Design

Concept, Rules and Requirements

Marble Maze Concept

Lean Game Production

Getting the Ball Rolling

Create a Game Scene

A Ball With Physics

Preview Tilt Control

Cross-Platform Controls

Unity’s Virtual Control System

The CrossPlatformInput Package

Write Control Code

Using a Gamepad

Cross-Platform Input Code

Use an Input Variable

Rotate Object From Code

Create a Sensitivity Control

Polish and Deploy

Fix Obvious Issues

Convert Project to Web

Sharing Your Web Game

Next Steps


Is Unity for Me?

Unity is a video game development environment, popular with professional and amateur game developers. Unity can deploy games to a very wide range of platforms from a single unified base (hence the name). You can deploy your game to mobile, console, PC and much more.

Unity has been gaining respect within the industry for many years. It already has over 80% of the indie developer market, and with the recent improvements in graphics and professional tools, it is becoming a tool of choice for large game houses too.

Whether you’re a keen amateur or a game studio looking for a serious development platform, Unity deserves your attention.

This practical guide will get you off to a good start.

Is Unity Just for Making Games?

Actually, no! Unity makes it very easy to develop mobile, desktop and browser applications. Furthermore, you can access geolocation, accelerometers and more. This makes Unity a great tool for any graphics-intensive application, particularly when you want to deploy to multiple platforms.

Companies have used Unity to create product showcases, augmented reality applications, training programs, and much more.

How to Use This Guide

This free guide is designed to help you get into Unity without any programming or game development experience.

If you do have experience, skim through and look for parts that will be useful to you. Note that there is a clickable table of contents at the top of the page, and that you can download our starting point for most exercises.

To get the most from this guide, it is important for you to be active. That is, have a copy of Unity open while you read, and follow along with the exercises. You only truly learn by doing. When you see Cmd / Ctrl + Key I am giving you the PC / Mac alternative, respectively.

If you’re wondering when you should be active and when you should just read, look for the numbered lists. A 1, 2, 3 list will be a series of steps designed for you to follow along with. If you leave the guide, remember to save your work so it’s ready for you when you come back to it.

Have fun, and feel free to keep a shortcut to this page.

How to Set Up Unity

About Unity Versions

To run Unity, you’ll need a reasonably modern Mac or PC; read the system requirements on Unity’s site if in doubt. Let’s dive in and get Unity installed. If you’ve already done this, feel free to jump to the next section.

Using an Older Version

We will be using Unity 5, so if you’re running an older version, it would pay to upgrade first. If you don’t want to upgrade, Unity 4.6 should be fine too; there will just be some minor differences and extra features in Unity 5.

There are two versions of Unity 5, Personal and Professional. We will be using the Personal edition, which is completely free until you earn $100,000. See “Which Version You Can Use” in Unity’s Licence Agreement for full details. This is an amazing opportunity to use a very powerful system for free.

Downloading and Installing

Installing Unity is as simple as any other piece of software. You will need to register with Unity if you don’t already have an account, but don’t worry, they respect your email address. There are a few things to consider when installing, however – hence this part of the guide, which you can skim over if you already have Unity installed.

Running Multiple Versions of Unity

If you want to keep a previous version of Unity installed, simply re-name one of your program folders, and leave the other one as Unity. For example, if you want to keep version 4 installed, then rename your program folder from Unity to Unity 4 before running the installer.

Be aware that when Unity updates itself in the future, it will update the version in the folder called Unity.

Follow these steps to get Unity installed:

  1. Download the Unity installer from the Unity download page.
  2. Run the installer like you would for any other piece of software.
  3. Leave Unity 5, Web Player and Standard Assets checked as below.image22

    image18Choosing which components to install on Mac (above), and Windows (below)

  4. If you don’t mind Unity overwriting any previous versions, leave the default install location. If you want to install Unity 5 alongside an older version, see the tip below.
  5. The download will take some time, as it’s over 1.5 GB in size.
  6. Log in if you already have an account, or create a Unity account here. You’ll need to check your email to verify your address.
  7. Well done – the Unity installation is complete.

Running Unity Via Virtual Desktop

Here’s a cool tip for you if you’re on a device that can’t run Unity, but have access to a machine that can. You could run desktop sharing software and access Unity remotely on your netbook, Linux machine, Chromebook, or even iPad.

Creating a New Project

When you first start Unity 5, you will see the project dialog below. Simply click New Project to get started.


image23The project dialog the first time you run Unity, on Mac and Windows

Once you’re inside Unity, you can create a new project from File > New Project, or open an existing one using File > Open Project… pretty standard stuff!

Below is the default interface of Unity. This is where you’ll be spending a lot of your time. There is one other program to consider, MonoDevelop, which is an Integrated Development Environment (IDE) for writing your code.


image25How to add new tabs, on Mac and Windows

As you can see from the screenshot, the interface is made up of several “Tabs”, such as Hierarchy, Scene, Game, Inspector, Project and Console. You’ll also notice that Mac and Windows versions are very similar looking, so from now on I’ll only include Windows screenshots if the differences are significant.

Even though you may not understand what any of them do, let’s get comfortable with the interface now.

  1. Try grabbing the bars between tabs to re-size them.
  2. Try adding new tabs by right-clicking as shown above.
  3. Grab a tab and drag it to detach the window.
  4. Revert to the default layout by clicking Layout at the top right. (see below)


Getting back to Unity’s default layout

Dive Into C-Sharp (C#)

We will be teaching you to write games in C#. This is pronounced “C-Sharp” but written C# like the musical notation. C# is a powerful, modern and highly transferable programming language that forms the basis of Microsoft’s .NET framework. Better still, this has just been made open-source, making it an even more valuable language to learn.

Languages Unity Supports

It is also possible to code in UnityScript, a variation on JavaScript. However, there are some restrictions to what is possible. This guide will be focusing solely on C#. Unity formerly supported Boo, which has since been discontinued.

Why We’re Coding First

Brian Tracy has written a book called Eat That Frog! The idea is that if you have something unpleasant to do, do it first. Unity has a lot of bells and whistles, and the temptation is to dive in and start making pretty things bounce around. While this is extremely satisfying at first, the reality is that you need to know how to code to make a unique game.


Image from Wikipedia, created by Brian Gratwicke.

We’ll focus on learning the basics of code before we start playing with the pretty stuff. That way, when we do get to the more advanced tools, you’ll understand how to use and modify them properly. Getting this done now will greatly improve your experience with Unity.

Writing Your First Script

Unity comes bundled with an Integrated Development Environment (IDE) called MonoDevelop. This is like a text editor, with some extra features to help you write scripts more quickly and accurately.

Using Visual Studio With Unity

If you’re more advanced and prefer a different IDE, it is possible to use Visual Studio with Unity. However, doing so is beyond the scope of this guide.

You must save your file in MonoDevelop in order for Unity to notice the changes. Let’s dive in and write our first code.

  1. Find the Project tab (at the lower left by default), and right-click in the Assets pane. Choose Create > C# Script. Name the script HelloWorld. Unity will automatically add a .cs (C-Sharp) on the end.
  2. Drag this new script onto the Main Camera in the Hierarchy. Scripts must be attached to objects to run.
  3. Note that when you “Inspect” the Main Camera, there is now a script attached.image20How to attach a script to a game object
  4. Double-click the script in your Assets, and after a few seconds, MonoDevelop should open. All new scripts start looking like the one below. For now, let’s focus only on what we’re going to write inside the Start () method on line 8. You’ll learn what all this means later.


    image33How MonoDevelop appears on Mac (above) and PC (below)

  5.  It is a programming tradition to start with a “Hello World!” exercise, so let’s not break that tradition. Add the following code on line 8, as shown above: print (“Hello World”); exactly as written.
  6. Save your file in MonoDevelop with Ctrl/Cmd+S. This will allow Unity to see the change.
  7. Go back to your Unity window, and hit the Play button (or click Edit > Play). You should see your message in the console tab as shown below.image15

    How to run your “game”, and see the Console output


How to Rename a Script in Unity

If you want to rename your script, do it from within MonoDevelop by highlighting the name after the word class, and using Cmd/Ctrl + R (for Rename). Type the new name, starting with a capital letter, leave the checkbox ticked, and click OK. This will rename the class (more on that later) and the file name for you.


Renaming a script in MonoDevelop


Congratulations – you’ve written your first line of code. This process of writing scripts and attaching to game objects underpins how you will customise Unity to your needs. With some experience and careful planning, your imagination becomes the only limit to what you can do with Unity.

C# Syntax Basics

It’s all fine and good to copy and paste my code. Of course it worked… I had the unfair advantage of trying it before I wrote it. What we really need is for you to learn why the code is written that way.

Again, don’t worry about the context for now; let’s learn to code “inside out”. That means you should understand this line, then Start (), Update (), etc., before eventually understanding the cryptic looking public class HelloWorld : MonoBehaviour {} and other code.


The code we wrote in a monkey-see-monkey-do fashion


Note how MonoDevelop has highlighted the string in orange for us. Try removing the first and you will see that the orange highlight doesn’t start until later in the line. Furthermore, the whole line of code is now invalid, because MonoDevelop is expecting a string inside print (); Try this yourself by hitting Cmd/Ctrl + B. This will Build your project, and check your code.


The errors caused by missing a character

You can see from this string of errors that it’s pretty important that you write your code precisely. Even a single missing character can cause what seems like a whole load of trouble. Don’t worry – once you put the leading “ back in, all will be good in the world again. The following notes are especially important:

Now that you know how to follow along, we will do the rest of our learning “in context”, by actually making games.

Basic Game Design

In this section you will make your first working game in Unity. I believe the best way to learn is in time and in context. That means we will focus on one clear outcome, then learn what we need exactly when we need it, and in the context of the problem we are trying to solve.

Concept, Rules and Requirements

I’m a great fan of “just doing it”, but a certain amount of planning is vital. Imagine you’re doing a jigsaw. The minimum planning necessary is making sure the table you’re using is big enough… otherwise moving it could be messy. It’s the same with your game.

Here are three things to consider when do your initial plan:

Concept What’s this game about? Imagine you’re telling your mate.
Rules Can you win / lose? How? What other rules are there?
Requirements What assets will we need? 2D / 3D Art? Music? Sound?

By just taking the time to write these things down, possibly with a few sketches, you’ll be surprised how much it helps keep you on track later. This is especially important when working with other people, so that you’re literally all on the same page!

Start With Simple Games

It’s a common mistake to try and think of an original idea for your first few games. It’s much better to “learn the ropes” with a known concept. That way, you can hone your development, deployment and marketing skills before unleashing your dream game on the world.

Marble Maze Concept

Concept A simple physics-based “marble maze” game. The idea is to tilt the play space, and get the ball into the goal.
Rules The ball must come to rest in the bottom of the hole to win. If the ball leaves the play space, you lose.
  • Two maze 3D models to act as the first two levels.
  • A ball rolling sound.
  • A sound for the ball hitting the walls.
  • A gamepad if you want to try controlling that way.

For tilt control…

  • A USB cable
  • The Unity Remote app
  • An iOS or Android device*

*No Windows Phone at this stage, I’m afraid, as it requires a special Unity plugin.


A rough mock-up of our play space

For the purposes of this guide, we will supply the 3D models required. If you want to learn more about 3D modelling, see The Complete Blender Creator.

Lean Game Production

We will be practicing lean game production. This means that we will be trying to minimise waste caused by mistakes by getting a basic version of our game working as soon as possible. We will continually focus on getting our game into a playable state, on a real target device, so that we can get player feedback.

We will organise our workflow so that it is easy to make changes later. That way, we can keep iterating our design until it’s just right. We don’t really know what’s going to work until we see emotion on a player’s face, and anything getting in the way of that happening is “fat” in the production process that we need to cut out.

Shipping means getting the product out into the wider world for feedback. It’s scary, but it’s vital. Seth Godin has done a lot of great work which will help you combat any “resistance” to shipping.

Getting the Ball Rolling

In this section we will create our first “scene”. A scene is a collection of assets such as models, sound, etc. Some games use one scene per level; other times, everything can be done in one scene. In our case, we will start off with a single scene.

Create a Game Scene

To get your scene set up, and your board imported, follow these steps:

  1. Create a new 3D project as described above.
  2. Save your first scene immediately as Game by clicking File > Save.
  3. Download the Maze01.fbx model. Import it into your Assets folder as below:image13Right-click in Assets tab to bring up this menu
  4. Drag this model from your Assets to your Hierarchy to create an instance of this model in your Scene.image29How to drag the model into your scene / hierarchy
  5. Congratulations – you have imported your first 3D model in Unity.

About Hierarchy and Scene

The hierarchy is simply a text representation of everything in this scene. So the Game.unity scene contains a Main Camera, Directional Light and Maze01 3D model.

A Ball With Physics

The maze play space is very basic right now, and that’s fine. It’s what we call a placeholder asset. The biggest thing stopping this game being fun right now is the lack of ball, and the inability to tilt the play space. Add a ball as follows:

  1. Open your project, or download ours.
  2. Click GameObject > 3D Object > Sphere to add a sphere to the scene. Re-name the Sphere to Ball, either by clicking it twice slowly in the Hierarchy, or by renaming at the top of the Inspector and hitting enter.
  3. Move the Ball to (0, 0.6, 0) by setting the Transform values in the inspector. We will make the ball look prettier later.image07Re-naming, and setting the transform position of a game object
  4. Add a Rigidbody to the Sphere by clicking the Add Component button at the bottom of the inspector, and choosing Physics > Rigidbody. This will make the physics engine control the sphere.image06Adding a component to a game object in Unity
  5. Select the Main Camera in the Hierarchy, and Position it at (12, 10, -10). Set the Rotation to (40, -50, 0).
  6. Play the game and notice that the ball falls through the floor. This is because the Maze01 game object does not a have a “collider” required for it to act like a solid object.

    About Play and Play Mode Tint

    When you click the Play button, certain windows in the editor are tinted a different color. Any changes made in these windows are not applied while in Play mode. Be sure to click the Play button again before making changes you wish to save.

  7. Expand the Maze01 game object in the Hierarchy, and find the Maze Mesh child object. Add a Mesh Collider to the Maze Mesh child by clicking Add Component > Physics > Mesh Collider in the Inspector. Depending on how the menu was last set, Mesh Collider may not appear in the list. You may have to type “mesh” in the search box to get to it, or clear the previous search by clicking the little x.image24Selecting the child maze object (the actual mesh), and adding a mesh collider
  8. Run the game again, and note that the sphere now rests on the surface. If the ball still falls through, check it is definitely the child object you added the collider to, not the top-level Maze01 object.
  9. Congratulations – you’re making rapid progress.

Preventing the Player From Getting Stuck

If you have strong attention to detail, you may have noticed that I put the sphere in the scene 0.1 game units above the ground (it has a radius of 0.5, and we placed it at 0.6). I did this to prevent it getting stuck in the ground.

So, to recap, so far we have added two game objects to Unity. The ball is a primitive object, so we used Unity’s built-in sphere. The maze is more complex, and was created in Blender and imported as a .fbx file. This is a common file format for imported assets. Unity does support opening Blender files directly, but you would need the program installed – hence supplying a .fbx.

We then added “colliders” to both objects. These tell Unity’s physics engine where the objects are, and prevents them from passing through one another. We also added a rigid body to the ball. This gives the ball mass, and makes gravity act on it. We will be tweaking the physics later.

Preview Tilt Control

Soon we will need to write some script to get some controls (e.g., keys, mobile device’s accelerometer, a gamepad, etc.) to move the maze around. However, we can preview the effect of this without doing any coding as follows:

  1. Open your project, or download ours.
  2. Play the game, and select to the Scene tab. The physics engine will now be running, but we can manipulate objects forcefully.
  3. Select the Maze01 object in the Hierarchy, and then chose the rotation tool (or the E key). You can now drag the “ball” in the scene view to rotate the object. Dragging on the colored lines restricts the rotation to one axis.image29Using the rotate tool in Play mode
  4. Note that the ball doesn’t currently move. This is because the ball starts resting on the play space, and the moment we rotate the place space the ball gets stuck inside it before it has a chance to move.
  5. Stop the game from running by clicking Play again. This is important because any changes you make while the game is playing will be lost when you stop playing.
  6. Drag the ball inside the Maze01 game object in the Hierarchy. This will make the ball move with the play space. When done right, the ball will be at the same indentations level as the Maze Mesh.image32The Hierarchy before and after “childing”
  7. Play the game again, and rotate the Maze01 object as you did above. Now the ball should roll around the space.

This may be simple stuff, but Unity is doing a lot of work for us here. If you had to write all this from scratch, it would take weeks or months, even for an experienced developer!


Your “game” so far.

Monkey See – Monkey Do?

You may be wondering if you are really learning Unity by following me. I’m a firm believer in challenging you to do things yourself, and in my Unity video course we do this all the time. However, in this written format it’s too easy for you to “cheat” by looking ahead, so I’m trying to focus on just telling you what to do and explaining why.

Cross-Platform Controls

You’ve already had a glimpse of the power of Unity’s physics engine. Now we are going to explore another one of Unity’s strengths: its ability to deploy a game to many platforms from the same code base.

Without additional licences or modules, you can deploy your game to:

… and with additional modules and licences, you can deploy to all the major consoles, and Windows phones too.

One Size Doesn’t Fit All

While it’s amazing to be able to deploy to this many platforms, most games benefit from being designed for a small number of platforms. Even the biggest game studios can struggle when they try and stretch a game too far, usually because of the fundamental differences in control systems.

Unity’s Virtual Control System

In order to make best use of this cross-platform ability, we need to use a “virtual” control layer. This sits between the physical controls and your code, and is one of the things that makes this cross-platform ability possible.


Visualising a virtual control layer

Many of the tutorials and forums on the web will be using a code “class” called Input. to process user input. We will be using CrossPlatformInputManager. It’s a bit of a mouthful, and takes a couple more steps, but it will be worth it when you get to switch your game from web, to Mac, to mobile and more effortlessly.

The CrossPlatformInput Package

We’re going to import our first standard Unity asset pack. This contains a lot of very useful scripts and “prefabs” (prefabricated game objects) for making our game work on many devices.

  1. Open your project, or download ours.
  2. Click Assets > Import Package > CrossPlatformInput. If you don’t have this in your menus, download the asset pack from Unity’s website here.image35How to download Unity’s standard assets pack if missing
  3. Import the whole asset pack by leaving all the boxes checked, and clicking Import.image16Importing all assets in a pack
  4. Confirm that the pack has imported by looking in your Project tab, and finding CrossPlatformInputManager.cs in Assets > Standard Assets > CrossPlatformInput > Scripts.image31Finding a script in the standard assets pack
  5. Well done – you’ve learned another useful Unity skill: importing asset packs.

Note that the package will have also installed a folder called “Editor”. Leave this as is, as the package may need it to function correctly.

Use the Asset Store

Another of Unity’s huge strengths is its thriving Asset Store. This is an online repository containing thousands of free and paid-for assets, including useful scripts, 3D models, 2D sprites, and much more.


You can find free assets by simply searching right inside the Project tab.


Write Control Code

It’s time to get back to coding. In this sub-section, we will write some simple but powerful code that will allow us to tilt our maze, using the keyboard at first. We will then explore how to make this work with gamepads, and even tilt-sensors on your mobile device.

It’s Not Really Moving

A movie is simply a fast sequence of still frames. A game works the same way, giving the illusion of movement by rapidly playing one frame after another. In between these frames, little or nothing happens in the game. It is our job to make sure that the frame rate is at least 24-30 frames per second (FPS) to maintain this illusion.

In the introduction, you saw how to call a method inside Start(), and I explained that this code will be run when the game first starts. This time, we need the code to run “continuously”, or more precisely, the game must respond to input every frame. To do that, we’ll put our code inside the Update() method. Let’s see how:

  1. Open your project, or download ours.
  2. Create a new script TiltControl.cs, and attach it to the Maze01 object. You can do this by right-clicking in Assets and choosing Create > C# Script. Drag it to the Maze01 object in the Hierarchy to attach it.
  3. We need access to the CrossPlatformInput module we just imported, to give our TiltControl.cs script access to this. Double-click the script to open it, and add this line at the top of your script: using UnityStandardAssets.CrossPlatformInput;. The order of the using statements doesn’t matter.
  4. Inside the Update() method add the following line to print the value of the “Vertical” control axis to the console:

    print (CrossPlatformInputManager.GetAxis ("Vertical")) ;

  5. The final code of TiltControl.cs is below. Now save your script and attach it to the Maze01 parent game object.image37The tilt control script at this stage
  6. Hit Play to start the game. Click on your Console tab so you can see the print statements.
  7. Finally, click into the Game window, then press the up and down arrow (or W and S) on your keyboard. You will see the values rapidly approach +1 and -1, respectively.image02Input values printed to console (must be in Play mode, and clicked in Game tab)
  8. Well done – you are reading control input.

Let’s break that line of code down:

print (CrossPlatformInputManager.GetAxis ("Vertical"));

First, we have a print (); method that we saw before. Inside the brackets, this statement expects something it can print. CrossPlatformInputManager is something called a class. This is collection of related methods, or recipes for doing something. Think of it like a specific cookbook, if you like.

One of the methods of this class is GetAxis (). This method takes in a string to tell it which axis to “get” the value of. In our case, this string is “Vertical” . The GetAxis () method returns a value – in this case, something called a float, short for a floating-point number. This is a decimal number which can take a large range of values, but in our case, -1 represents fully down, and +1 fully up.

Why the Keyboard Value Isn’t Just +/- 1

You’ll notice the value coming from your key-presses doesn’t go to +/- 1 immediately by default. This is something called “gravity”, and it helps the keyboard controls respond more like a trackpad or tilt. You can read more about this in Unity’s docs here.

When writing your code, MonoDevelop helps you understand methods as you type. For this to work the code above, what you are typing must “compile” – that is, make sense to the computer. If it does, you will get a tip coming up as shown below:


MonoDevelop intellisense

Using a Gamepad

Our game is ready to accept input from a gamepad without any further work. Simply:

  1. Connect your gamepad the way you usually would; Play your game.
  2. Click into the Game window.
  3. Move the left stick up and down. You should see the value in the console change.

Unity Isn’t Responding to My Gamepad

The gamepad must be connected when Unity opens. If Unity isn’t responding to your gamepad, then close Unity, check that your gamepad is connected, and re-open Unity.

Keep your gamepad handy if you have one. In the next section, we will make our controls actually tilt the playspace, and the fun will really begin.

Cross-Platform Input Code

In this section, we will actually move the play space. There will be a few new programming concepts to introduce, including variables, a new type called Vector3, and how to access an object’s “transform” to rotate it.

How to Declare Variables in C#

The general pattern for declaring variables in C#, and giving them an initial value, is:

type varName = initialValue;

The type will usually start with an uppercase letter, except for some common built-in “primitive” types like float, string and int. The convention is to write the variable name with a lowercase first letter, but uppercase midway to emphasise words is fine.

The initialValue must be of the same type as declared on the left. That is, a string must be stored in a string, a float in a float, etc.

Use an Input Variable

As the value of the horizontal and vertical axis input varies from -1 to +1, we need to somehow tell Unity to rotate the maze by a number of degrees proportional to that. For example, we may decide that pushing the control stick all the way up (a value of +1) leads to a rotation of 90 degrees, or 30 degrees. This is our choice of control sensitivity, which you’ve probably seen in the menu of your games.

Because this value will vary while the game is playing, we need something called a variable. In this case, we need to store two floating-point numbers for the horizontal and vertical input values. C# comes with a handy structure for storing three floating point numbers, called Vector3.

Why three numbers, and why Vector3? Because even though we are not rotating in the y-axis this time, in general we may want to. Also, when we come to rotate the maze in the next sub-section, we will need to supply a Vector3 so we might as well start with one.

  1. Open your project, or download ours, and open the TiltControl.cs script.
  2. Just inside the Update () method, add Vector3 inputValue;. See the screenshot after this exercise if unsure.
  3. Change the next lines inside the Update() method to the following:inputValue.x = CrossPlatformInputManager.GetAxis ("Vertical");

    inputValue.y = 0f;

    inputValue.z = CrossPlatformInputManager.GetAxis ("Horizontal");Now, instead of the input value being sent to the print method, it goes into the appropriate component of our new variable.

  4. Replace the print line so that we can see what’s being stored in our variables:print (inputValue.x + " , " + inputValue.z);

  5. Save your script, and Play the game and look at the console, or easier still, the very bottom-left of the screen in Unity, which shows the last console output. You should now see the values for both the horizontal and vertical control inputs (keys or keypad).
  6. Well done – you’re getting close!


The current state of our control code


Why Write 0f In C#

The f after the zero tells C# that this is a float. In the case of zero, this can be left out, but it’s good practice to write it in for now because if it was any other number than zero, you would get an error if you didn’t explicitly tell the computer what type your number is.

It is tempting to try and read the input value, and use it to set the rotation one step. However, if it doesn’t work, it can be very hard to work out what’s going wrong. It doesn’t take much extra time to check that the values are correct in the console before trying to use them like this, and will often save you a lot of head-scratching later!

Rotate Object From Code

Here we’re going to find out how to manipulate a game object’s transform from code.

  1. Open your project, or download ours, and go back into your TiltControl.cs script.
  2. At the bottom of the Update method, add the line below. It must come at the bottom because we can’t use the variable until after we’ve declared it:transform.eulerAngles = inputValue;
  3. Play the game, click into the Game window, and try using the cursor keys (or WSAD). If you have a gamepad, try that too. Note that the play space tilts, but only a tiny bit – in fact, it’s only tilting 1 degree.
  4. Well done – you have working cross-platform controls. Now we need to implement control sensitivity.

Here’s the line of code we added:

transform.eulerAngles = inputValue;

The transform.eulerAngles on the left-hand side corresponds to the transform component of the game object that the current script is on. Because TiltControl.cs is on the Maze01 gameobject, transform corresponds to that rotation of Maze01.

The .eulerAngles bit is the way of accessing the rotation property of the transform. This is equivalent to setting the rotation in degrees in the inspector, but of course your player can’t do this when the game is running, so this is how to do it in code.

image36Accessing the rotation from script


Local vs. Global Coordinates

When you explore Unity on your own, you will come across local vs. global coordinates. In this simple game, with the maze at the origin with no rotation, there is no difference between the two for all practical purposes. However, be aware that there is a difference. There is a reasonable explanation here, among other places.

Create a Sensitivity Control

A one-degree tilt does not necessarily make for an exciting game. So, here’s how to use another variable to allow you to tweak the control sensitivity. In a more advanced version of this game, you could even create a User Interface (UI) to allow your player to change this for themselves. It is our job to find a workable starting point, however.

  1. Open your project, or download ours. Go back into your TiltControl.cs script once more.
  2. We need a variable that is accessible in the inspector. To do this, add the following line of code under the “class definition”:public float sensitivity = 90f;

    Remember to indent your code using the Tab key. When you have finished, it should look like this:

    image03Where to add a public variable


  3. Now edit the line that does the rotation to multiply the input values by the sensitivity:transform.eulerAngles = inputValue * sensitivity;In this case, we will now be rotating +/- 90 degrees because as the components of the input value vary from -1 to +1, they will be multiplied by 90.
  4. Save your script, and Play the game again, and note that the rotation is now a full 90 degrees. Using values you can visually verify like this at first makes sense.
  5. Stop the game, and click on Maze01 in the inspector. Note that you can now change the sensitivity in the inspector now. Set the value to 30, to make the maximum tilt 30 degrees.image14

    Setting a public variable in the inspector

  6. Play once again, and notice that the maximum tilt is lower. Experiment with changing this value in Play mode, and when the game is stopped. Note that the value is not kept if changed in Play mode.
  7. Finally, note that the camera is in an awkward place to play the game. We’ll fix that later, but for now, let’s pretend we missed it and carried on to ship our game.

Public Values in Code and Inspector

Note that we gave our sensitivity control a value in the code (90 degrees), and another one in the inspector (30 degrees). You may wonder which one takes precedence, and isn’t it dangerous to have a value in two places.

The value in the inspector overrides that in the code. However, it’s still a good idea to set a sensible starting value in the code.

Polish and Deploy

Our game is far from perfect at this stage, but it is playable. Let’s fix the obvious issues, then share to get our very first feedback. The reason is to spot things that we’re too close to notice, and fix them super early.

Fix Obvious Issues

Before I’m willing to share this with anyone, I would want to at least sort out the following glaring issues. Be careful, though, as it’s tempting to never “ship” your game because of perfectionism. Get the basics working, and share your game.

Here are the three, and only three, issues we’re going to fix for now.

  1. The ball moves too slowly. Why? Because the physics engine is set up to simulate 1 world unit = 1 meter by default. That means we have a 1m diameter ball, on a 16m play space. That’s like a huge beach ball on a tennis court – no wonder it’s slow! We’ll fix it by increasing gravity at least 10 times.
  2. The controls don’t “line up” with the screen. This is because we haven’t tried to make them line up yet. The maze has an arbitrary rotation, and we need to make some changes to get the controls lined up. However, at the same time, we must take care of the next problem.
  3. The viewing angle is awkward. In our haste to get to a working game, we didn’t really think about the camera angle. That’s a good thing, because you don’t really know how you want it until you can play it. Now that we can play it, it’s time to fix the camera angle and the control alignment at the same time.

Let’s fix all three of these issues at once.

  1. Open your project, or download ours.
  2. Move the Main Camera to (0, 10, 8) with a rotation of (50, 180, 0). This helps with the view, but now the vertical controls are reversed.
  3. Open TiltControl.cs and modify the line below by adding a minus sign after the = sign. This will reverse the vertical control values. Remember to save your script.

    inputValue.x = - CrossPlatformInputManager.GetAxis ("Vertical");

  4. Make sure your game is NOT in Play mode, and click Edit > Project Settings > Physics. Set the Gravity Y scale to -100, about 10 times bigger than it was but still pointing down. This will accelerate the ball faster.image12

    Increasing the gravity scale of your game

  5. Play the game again, and note that it’s all much nicer now.

Convert Project to Web

In this sub-section, we will show you how to use Unity’s “Build Settings” to change the target platform of your game to WebGL. This feature is new to Unity 5, and allows you to make games that run in a browser using HTML 5, without the player even needing a plugin.

Here’s how to convert your Unity project to a web build.

  1. Open your project, or download ours.
  2. Click File > Build Settings to bring up the platform build settings.
  3. Add the Game scene by either clicking Add Current, or dragging it from the Project tab into the “Scenes In Build” panel.
  4. Under Platform chose WebGL, and click Switch Platform.image05

    Build settings for deploying to the web



You now should have a fully functioning game in the web. There are a couple of limitations: the gamepad controls won’t work. For that, you’ll need to build again for PC, Mac or Linux. Also, you’ll need to use Chrome, Firefox or Safari as a browser.

You can also build to “Web Player”. This will work in Internet Explorer, and the gamepad input will work. However, your player will need the Unity plugin installed.

Sharing Your Web Game

If you want to share your game, you could zip and send the marble folder to a friend for him or her to play locally. Alternatively, you could “host” this file on some web hosting if you know how to do that.

If you have a paid version of Dropbox, you can simply put it in your Public folder and share the public link. There will be a limit to how much bandwidth you can use this way. You can play my version on Dropbox here.

Next Steps

Thank you for reading this guide. If you have just skimmed through it, then I encourage you to take some time to go back and follow the exercises through. Remember, you don’t need to do all of them, as I provide a starting state for every exercise for you to download.

Please continue your Unity education by searching for YouTube videos, and consider enrolling in our epic 50-hour Udemy video course.

If you prefer the written format, you can pre-order my upcoming book from Amazon.

It’s been a pleasure teaching you.

Ben Tristem

Page Last Updated: August 2015

Top courses in Unity

Unity Android Game Development : Build 7 2D & 3D Games
Raja Biswas, Charger Games
4.5 (1,594)
Unity Dialogue & Quests: Intermediate C# Game Coding
Sam Pattuzzi, Rick Davidson, GameDev.tv Team
4.6 (458)
Learn to Write Unity Compute Shaders
Penny de Byl, Nicholas Lever, Penny @Holistic3D.com
4.6 (165)
Unity Multiplayer: Intermediate C# Coding & Networking
GameDev.tv Team, Rick Davidson, Nathan Farrer (aka Dapper Dino)
4.4 (1,266)
Unity Game Developer Masterclass 2021 (2D, 3D and FPS)
Denis Panjuta, Tutorials.eu by Denis Panjuta
4.7 (259)
Bolt Visual Scripting in Unity
Wilmer Lin
4.6 (234)

More Unity Courses

Unity students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.

Request a demo