Unity Tutorial: Hello World for iOS

In this first in a series of Unity tutorials (with an emphasis on mobile game development for iOS) we will build a very simple game in which the player must tap the screen to keep a box in the air for a specific amount of time. We will discuss how to get touch input into the iPad and how to build a Unity project for iOS.

Start off by creating a new 2D project. In the project view, create Prefabs, Scenes, Scripts and Sprites folders, and save the current scene. Import some sprite (i.e. white box etc.) into Sprites and add it to the scene at (0, 0). This sprite will be our player item, so add a Box Collider 2D (or circle collider 2D if you have a humanoid sprite) and a Rigidbody 2D so that we can be affected by gravity and determine collisions with other objects.

If you run the game, your sprite should start falling downwards and out of the screen.

Rename this sprite Player and create and attach a script called PlayerJump in which we’ll jump when the user taps with their finger. Firstly go to Edit -> Project Settings -> Input and under Axes you’ll see that mouse 0 is assigned to Fire 1. Now we could use this button in our game, but instead lets set jump to Alt Positive Button so it is more explicit when coding.

Best of all we get touch-screen support for free as it is automatically mapped to mouse input. In PlayerJump.cs we simply add an upward vector force to our rigidbody whenever the player taps the screen.

Now we want to make a floor so we test when the player has fallen through it. Add a simple rectangle sprite to the bottom of the screen and add a Box Collider 2D. Now if you run the game, a mouse click will make the box jump, while the box will fall and rest on the ground.

However, this isn’t the behavior we want — we want the box to fall through the fall and be notified on collision. Instead change the collider to be a trigger and create and attach another script called PlayerScore.cs.

If the player survives 10s, then the game ends, while if they hit the floor, then the game also ends. Using OnGUI(), a label for the player’s score and time remaining are displayed on the screen.

Although very simple and not challenging to play, we have nevertheless created a 2D game in Unity! To build for iOS, go to Build Settings and add the current scene to the build list, change platform to iOS (download the library if you haven’t already) and then select a location to save the built files.

Once this is built, there will be an Xcode project which can be built (you need to be part of a development team) and deployed to a device.

So thats it for today. The full source code can be found here. Next day we’ll consider a simple infinite runner!