Unity for Windows: I – Getting started

image

Hi, and welcome to the first part of the Unity game programming for Windows tutorial series. This  first part will introduce you to Unity and help you create your first simple game. In part II and III we will export the game for Windows 8 and Windows Phone 8.

DRAFT VERSION

Unity?

Unity is a game development engine that let’s you export your game to multiple platforms (Mac, PC and Linux desktop computers, Windows Store the Web, iOS, Android, Windows Phone 8, Blackberry 10, Wii U, PS3 and Xbox 360.).

image

Unity comes with a development environment for building your game, and then your logic is written using C#, JS and/or Boo.

Basically it’s a complete toolset for creating games (or other interactive projects) making game development easier and saves you a lot of time due to its rapid approach.

image

Many indie game developers use it to save costs, and get their product out to as many markets as possible. Rovio (creator of Angry Birds) used Unity for their game Bad Piggies, and a lot of other known games is created using Unity.

Unity comes in two versions, one FREE and one PRO. I’d recommend you to start with the free version as it comes with absolutely everything you need to create games and export them to many platforms. The PRO version includes some advanced tools and performance tools. You can read more about it here.

Installing Unity

1) Download Unity

2) Install it on your computer

3) Start Unity

Creating a new project in Unity

When you start Unity for the first time it should present you with a screen for setting up a new project. It looks like this:
image

If not, click File->New project
image

In the Unity Project Wizard you can choose what libraries (packages) you want to include in your project. As we are creating a game for mobile devices, let’s add the Standard Assets (mobile) package (more can be added later using the Asset Store). The Asset Store includes all the free packages that followed, and you can also buy packages others have created.

image

When done, you will be presented with a view quite similar to this.
image

The layout might be different. You can change it to however you like it.

My layout is based on the Wide layout. You can change it like this.
image

Creating our game

Our first game will be very simple just to get your started. Later parts will create more advanced games.

A game consits of different scenes that you can use to “split” up the game in to different parts. In our game we are going to have three screens. One for the main menu, one for the game itself and one for the game over screen.

Game Design

The game will be in space, and your job is to defend your space ship from invaders. It will have a top down view. A canon will shoot a laser beam towards the location on the screen where you tap.

image

When your laser hits an enemy, it will die and you get score.

If an enemy hits the space ship, it’s game over.

Goal: survive as long as possible.

Implementing the game

The game will be in space, so we will need a black backdrop with some stars on it. We are going to need many textures so lets create a folder that will contain all of them. Right-click the Assets folder on the Project tab and click Create->Folder and name it Textures.

image

Now download this texture and save it in this new folder.

space

New, we are going to add this to our scene as a backdrop. To add our texture to any object on the scene, we will need to create a material, and apply the texture to this material. Create another folder called Materials under Assets.
image

In the materials folder, add a new Material and name it spaceBackground:
image

You should have something like this:
image

Click the spaeBackground material and some properties will be displayed, and then click the Texture folder and drag the texture space to the Texture property on the material.

image

Now the preview will show how a sphere will look like with the new material on it.
image

 

Now, our background can be created in many ways. In this tutorial we will simply create a plane that will dispaly our new material. To add a plane to the scene, click GameObject->Create Other->Plane

image

A new plane is added to the scene. This can be seen in the Hierarchy view.

image

The Hierarchy view contains two items. One is the Plane and another is Main Camera. Main Camera is what the player will see in the game.

Right now, what we see is the Scene view that is used to create the scene. You can always check what the Main Camera sees by changing the view to Game.

image

Do this now, and you will see a blue scene with a gray plane in the bottom.

image

First of all, we will need to rotate the plane so it covers the camera (we don’t want to see the blue stuff).

Change back to Scene view and click on the plane in the Hierarchy to display the properties. First of all, make sure the Position property is all set to zero.

image

Now, set the rotation property of the X-axis to –90

image

And then we need to scale it so it covers the entire screen. Set the scale on all axises to 5.
image

Now, let’s add our space texture to our new plane! Just drag the material from the Materials folder on to the plane in the Hierarchy view.
image

It still doesnt look good. The texture is very screched since the size of the plane is a lot bigger than the background texture. Click the spaceBackground material to bring up the properties, and change the tiling property to 8,8 (X,Y):

image

This will tile the texture 8 times in the x direction and 8 times in the y direction.

Now, this is better – but it’s still very dark! This is because the plane is using a Shader that calculates the diffuse light. And since we don’t have a lightsource in the scene, it will not be very visible.. let’s change the shader of the background from diffuse to background.

Click on the material to see the properties and change the Shader property (top) to Mobile->Background
image

It’s time to save the scene. Press Ctrl-S or File->Save Scene. Since this scene havent been saved yet, a save dialogue is displayed. Create a new folder called Scenes and name the scene “gameScene” and click Save.

Also, let’s change the Main Cameras position to be located at 0,0,-10 (X,Y,Z). Click the Main Camera and change the Position property:
image

This will set the camera to the center of the world and then 10 back on the Z axis (making us look in to the scene).

Creating the enemies
Next thing up is to create the enemies. We are going to create one enemy that will travel across the screen in a give speed.

First of all, we need the texture. Add the SpaceInvader.png file to your textures folder. You can find the texture in the tutorials assets zip file (download here).

SpaceInvader

When we added the space background plane, we created a Game Object that was a plane. A unity game is built up on different Game Objects. A Game Object is simply an object of any sort that is used to create the game.

A Game Object can be build up on many different game object. Our enemy will be created by having an empty game object as parent (hierarchy), and then a plane that will be the texture, and a particle engine that will be the enemys engine.

Click GameObject->Create Empty
image

A new GameObject is added to the scene. Click this to bring up the properties and change the name of the Game Object to “SpaceInvader”.

image

Also, set the position of the SpaceInvader to 0,0,-2
image

Also, rename the Plane that is our background to SpaceBackground by clicking on the Plane in the hierarchy overview and then changing the name property.

Now, we will add a material that will be the texture of the invader. Create a new material in the Materials folder and name it spaceInvader. Drag the SpaceInvader.png file from the textures folder to the texture property of the material and change the shader to Mobile->Transparent->Vertex Color

image

This shader will make the material alpha transparent based on the data in the png file (we do not want a black color on the parts of the texture where we are supposed to see through it).

Now, we will create a quad ( a plane but built up with less vertices) that will have the spaceInvader material, and it will be under the SpaceInvader Game Object we created earlier.

Click GameObject->Create Other->Quad

A new empty Quad is added to the scene. Now, we must drag the new quad to the SpaceInvader game object so the new Quad is located under the SpaceInvader hierarchy:

image
Drag Quad to SpaceInvader

image

The Quad is now inside the SpaceInvader Game Object and an arrow is displayed in front of it meaning something is inside it and it can be opened.

Clicking the arrow will open it, and you can see that the Quad is inside.
image

Rename the Quad to Spaceship, and drag the spaceInvader material on the new quad that now is named Spaceship and located inside the SpaceInvader object.

Since the Spaceship quad is inside the SpaceInvader, it’s X,Y,Z position will be relative to the parent game object (SpaceInvader). We want the quad to be in the middle of the SpaceInvader game object. So go ahead and change the Spaceship quads position to 0,0,0:

image

If you double click on a game object, the Scene view will zoom to the bounds of the object and put it in the center of the view. Double click the SpaceInvader object to set the focus to it.

It should look like this:

image

If you go to the Game View, it should be visible in the middle (since the camera is poining towards the middle and the invader is positioned there).

image

Notice that you can also see through the texture around the spaceship since we are using the alpha channel and a transparency shader on the material.

Making the enemy move

Ok, we have the enemy. But we need to make it move!

Create a new folder in the assets folder named Scripts.

image

Right click it and click Create->C# Script.
image

Name it “EnemyController”. A new C# script is added to the folder. First thing we want to do is to add this script to the SpaceInvader game object. Do this by draging the script on the SpaceInvader object in the hierarchy view.

image

If you click on the SpaceInvader game object to see the properties, you can see that the script is there as a new component to the SpaceInvader game object. A Game Object can be controlled and defined by adding different components. A script component can be used to script the behaviour of the SpaceInvader game object.

Now, double click the EnemyController to open the script in an editor. The MonoDevelop environement came with Unity and is used by default. I have changed this from the Unity perferences to Visual Studio 2012 since this is my perfered development environment.

You can also do this by clicking Edit->Preferences and change it from the External Tools tab:
image

The project is now opened in the development environment of your choice and the script can be modified to your likes.

What we will see is a script that contains two functions. One named Start() and another named Update(). Start() is called when the GameObject is loaded or added to the scene (when the scene starts), and Update() is called every frame.

using UnityEngine;
using System.Collections;

public class EnemyController : MonoBehaviour {

    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
   
    }
}

Let’s add a variable that will contain the speed of the enemy.

using UnityEngine;
using System.Collections;

public class EnemyController : MonoBehaviour {
    public float speed;
    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
   
    }
}

We want to move the SpaceInvader towards the left side of the screen. This means that we need to change the X-position of the invader with a small modification every time the Update() function is called. Remember, this needs to be small since the Update() function is called many times pr. second.

The reason we added the speed variable as a float is that we want to control the speed of each enemy (to be impleneted through scripting). Since the variable is public, it can be set directly in the unity environement! Save the script and click on the SpaceInvader object to view the properties.

You can see the Speed property in the script component of the game object. Set this to 5:

image

Moving the enemy based on time

We also need to think about how we move the enemy. If we move the enemy with –1 pixel pr. frame, the enemy will move faster on a computer that can render more frames pr. second than on a another one that doesn’t have the same performance.

Let me show you. If an enemy moves –2 pixels pr. frame, and a computer renders 60 frames pr. second, it will move –120 pixels pr. second. If another device renders the game at 30 frames pr. second, it will move –60 pixels in one second.

We want it to move the same distance on all devices, and fortunately the solution is very simple. We move the enemy based on the time – the clock!

Unity comes with a built in timer that contains the time of many things, including the amount of time it takes to render a frame in seconds!

Go to the Update() function and add the following line:

using UnityEngine;
using System.Collections;

public class EnemyController : MonoBehaviour {
    public float speed;
    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
        this.transform.position -= new Vector3(speed, 0, 0) * Time.deltaTime;
    }
}

What we are doing here is to modify the transform property of the Game Object the script is attached to with code. Since this scrit is attached to the SpaceInvader Game Object, it will transform the game object and everything inside the game object.

We change the position (X,Y,Z) by subtracting the position with a direction vector poining in the X direction. The magnitud is based on speed and then multiplied with the delta time it takes to render a frame.

If the frame is rendered slowly, this time will be greater and the movement will be bigger. If the frame is rendered quickly, the time will be shorter and the movement will be smaller.

Press play to see how the game runs! Smilefjes

image

Adding particles to the enemy

To create a better looking enemy in space, we need to add an engine to it. It’s moveing right? Well then it need the engine!

We can simulate a pretty good engine with a particle engine. Unity proveds a great tool on creating particle engines for all kinds of effects like explosions, fire, smoke, ressurection, level ups and everything you can imagine.

This part will not cover the particle editor in detail. A standard asset package (remember the packages we included in the project when we created it?) comes with Unity containing many particle engines that you can use and test out. Let’s add this pacakge to the project.

Go to Asset Store (the package is free) by clicking on Window->Assert Store
image

We already have the asset, so click on the Download/Import asset icon in the Asset Store menu:
image

Scroll down untill you find the Particles package and click Import. This will import the library to the project.
image

This will decomress the package and show you all the content of it. Everything is checked by default so just click Import again and there you go!

A new folder is added to the projects Assets folder called Standard Assets, with another folder in it called Particles:
image

Open the Particles folder, then the Smoke folder and drag the Smoke Trail prefab on the Spaceship game object inside the SpaceInvader game object.

image

A new particle engine is added to the SpaceInvader hierarchy:
image

If you press play now you can see the enemy creating a trail of particles behind it as it moves.

image

A prefab is a game object can be used many times in a scene. You can think of it as a factory that creates the a defined object. The enemy we now have created will be converted to a prefab later because we want to add many of the same enemy. We dont want to change all of them to make changes to them – so we change the prefab (the blueprint that we put in the factory) and all the items created with the prefab will be changed.

Let’s create a new folder to our project under Assets named Prefabs.

image

Think of what we have done with the SpaceInvader game object this far. We have created the blueprint of how we want the enemy to look based on putting together game objects, adding scripts, adding particles and materials. Now, we want to take this blueprint and get the factory ready to prouce them.

Do do this, simply drag the Game Object you want to create a prefab of to the Prefabs folder (or whatever other folder you want to put them in, it doesnt NEED to be named “Prefabs”). In other words – Drag the SpaceInvader game object form the Herarchy to the Prefabs folder:
image

The SpaceInvader object will appear as a name with a blue box in front of it, and the SpaceInvader in the Hierarcy view turns blue. This is because it’s based on a prefab!

Now, click the SpaceInvader object in the scene (from the hierachy view) and delete it.
image

Now it is gone..
image

Now, drag the SpaceInvader prefab to the herarchy view again:

image

It’s back!

Note: If you some time later (dont do anything now) go in and do changes to the item based on the prefab that you have added to the scene, like adding more components, game objects, particles, scripts, whatever to it, that part will become black since its not in the prefab. To update the prefab (and all items based on the prefab) with the new changes, just click the SpaceInvader object in the scene to view its properties, and click apply – all changes is then made to the blueprint that was used to spawn the object in the first place (the prefab).

Now, delete the SpaceInvader game object again since we want to spawn it with code later.

Creating a laser!

Next we want to create a laser gun that will shoot lasers when you tap/click on the screen. We will create the laser prefab! Create a new empty GameObject again:
image

Name the new GameObject “Laser” and make sure the position property of the new empty game object is set to 0,0,-2
image

Now, add the laser.jpg (from the tutorials assets zip file) texture to the Textures folder, create a new Material and drag the texture to it. Name the material “laser”.

laser

Change the Shader to Mobile->Particles/Additive (It will make it a bit transparent and they blend on to of other laser shots).

image

image

Now, add a new Quad to the scene by clicking GameObjects->Create Other->Quad
image

Rename the new Quad to LaserBody, and drag it to the Laser game object so it becomes a part of it.
image

Now, drag the laser material on the LaserBody quad and to give it color, and change the position and scale of the LaserBody properties to this:
image

This will position the LaserBody quad to 0,0,0 relative to the partent game object (Laser) and scale it so it becomes more laser looking than a square.

image

Now go to the scripts folder and create a new C# Script named LaserController, and drag it on the Laser game object.
image

Now, double click the LaserController script to edit it.

using UnityEngine;
using System.Collections;

public class LaserController : MonoBehaviour {

    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
   
    }
}

Now, we will do the same thing for the laser as we did for the enemy. We want to move it towards the right side of the screen in a constant speed. We dont want our lasers to have different speeds so we can leave that out as well..

using UnityEngine;
using System.Collections;

public class LaserController : MonoBehaviour {

    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
        this.transform.position += new Vector3(10, 0, 0) * Time.deltaTime;
    }
}

Should not be anything new. We move the laser based on a direction vector multiplied by the time it takes to draw a frame to sync it with the clock.

If you press play, you can see the laser moving over the screen. Now, let’s make a prefab out of it. Drag the Laser game object form the scene hierarchy to the Prefabs folder and delete the Laser game object that is in the scene (we spawn it by code later).
image

Spawning many enemies!

Next we need to spawn the enemies. I want to spawn an enemy with a random speed between 4 and 8, and at a random position in front of us.

Go to the Scripts folder and create a new script called GameController. Double click the script to open it in your development environment.

First of all we need to create two variables that will hold the Prefabs to our lasers and enemies.

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {
   
public GameObject enemy;
    public GameObject laser;

    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
   
    }
}

Then we need a timer variable that will time when a new enemy will be spawned.

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {
    public GameObject enemy;
    public GameObject laser;

    float spawnTimer;

    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
   
    }
}

Then when the scene starts, we want to set the spawn timer to 1.0f and the in the Update() function reduce this based on the deltaTime variable, making the spawn timer to be reduced by seconds. This means that if the spawnTimer is set to 1.0f, it will take 1 second untill the spawnTimer is 0.0f.

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {
    public GameObject enemy;
    public GameObject laser;

    float spawnTimer;

    // Use this for initialization
    void Start () {
        spawnTimer = 1.0f;
    }
   
    // Update is called once per frame
    void Update () {
        spawnTimer -= Time.deltaTime;
    }
}

Now, next we need to spawn a new enemy every second. We do this with a function that comes with Unity called Instansiate. I’ll show you the code first:

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {
    public GameObject enemy;
    public GameObject laser;

    float spawnTimer;

    // Use this for initialization
    void Start () {
        spawnTimer = 1.0f;
    }
   
    // Update is called once per frame
    void Update () {
        spawnTimer -= Time.deltaTime;
      
if (spawnTimer <= 0.0f)
        {
            GameObject instance = (GameObject)Instantiate(enemy,
                new Vector3(10,Random.Range(-4.0f,4.0f),-2.0f),
                transform.rotation);
            spawnTimer = 1.0f;
        }
    }
}

So, if spawnTimer goes equal or below 0.0f, we will create a new GameObject based on the prefab that is in the enemy GameObject variable defined earlier in the script (it is empty now) to a position of 10 units in front of us (thats outside the right side of the screen) and then having a random height between –4 and 4 (Y-axis). We also set the spawnTimer to 1.0f since we only want to spawn it once pr. second.

Now, let’s put this script in to use (remember to save it).

In Unity, go to the Scripts folder and drag the GameController script on the Main Camera in the herarchy view:
image

Now, click the Main Camera Game Object to view its properties. You can see that the script component is there and that the two GameObject variables laser and enemy is there:
image

Now, go to the Prefabs folder and drag the Laser prefab to the Laser property in the Game Controller (Script) component of Main Camera, and the same with SpaceInvader to enemy:
image

The reason we added the GameController script to the camera is a bit random. You can place it on a player object or anything, but since we dont have that I deviced to add it to the Camera and just use the camera as the main scene controller.. Smilefjes

Pressing play will start the game and you can see the enemies fly by the screen in different positions:
image

Pretty cool right?

Shooting lasers
Next, we want to shoot these invaders with lasers! To do this, we tap the screen and the laser will be shot to that location.

Unity lets you control Input very easily. Click Edit-Project Settings-Input to view the projects input properties…

image

…and open Axes and the Fire1 property.

image

Change the Positive Button from left ctrl to space:
image

You can also see that we have an Alt Positive Button that is set to mouse 0. This means that we can either use space or the left mouse button to let Unity know that the “Fire1” input has been made.

Now, back in the GameController script, we listen for the Fire1 event in the Update() function:

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {
    public GameObject enemy;
    public GameObject laser;

    float spawnTimer;

    // Use this for initialization
    void Start () {
        spawnTimer = 1.0f;
    }
   
    // Update is called once per frame
    void Update () {
        spawnTimer -= Time.deltaTime;
        if (spawnTimer <= 0.0f)
        {
            GameObject instance = (GameObject)Instantiate(enemy,
                new Vector3(10,Random.Range(-4.0f,4.0f),-2.0f),
                transform.rotation);
            spawnTimer = 1.0f;
        }
       
if (Input.GetButton(“Fire1”))
        {
            Vector3 spawnLaserPos = Camera.main.ScreenToWorldPoint(
                new Vector3(-5.0f,
                    Input.mousePosition.y,
                    8));

            Instantiate(laser, spawnLaserPos, Quaternion.identity);
        }
    }
}

What we do here is to check if Fire1 is hit, and if yes, we spawn a new laser at the left side of the screen, the height of where the player touched/pressed the mouse button using a handy function from the main camera that converts the touch/click location to world coordinates that can be used in the game.

And then we instansiate the laser.

Pressing play now, we can see that its possible to shoot a lot of lasers. We must limit this using a similar timer as in spawnEnemy.

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {
    public GameObject enemy;
    public GameObject laser;

    float spawnTimer;
   
float shootTimer;

    // Use this for initialization
    void Start () {
        spawnTimer = 1.0f;
    }
   
    // Update is called once per frame
    void Update () {
        spawnTimer -= Time.deltaTime;
       
shootTimer -= Time.deltaTime;

        if (spawnTimer <= 0.0f)
        {
            GameObject instance = (GameObject)Instantiate(enemy,
                new Vector3(10,Random.Range(-4.0f,4.0f),-2.0f),
                transform.rotation);
            spawnTimer = 1.0f;
        }
       
if (shootTimer <= 0.0f)
        {

            if (Input.GetButton(“Fire1”))
            {
                Vector3 spawnLaserPos = Camera.main.ScreenToWorldPoint(
                    new Vector3(-5.0f,
                        Input.mousePosition.y,
                        8));

                Instantiate(laser, spawnLaserPos, Quaternion.identity);
                shootTimer = 0.4f;
            }
        }
    }
}

Now, if we try to run it again, we can shoot but just every minimum 0.4 seconds! Smilefjes

image

Making explosions

Now, we have to deal with the collisions. We need to check if a enemy is hit by a laser.

Unity have a system where you can tag GameObjects. This is used to handle all objects with a given tag in a special way.

We are going to tag our lasers with a new laser tag, and our enemies with new enemy tag.

Go to the Prefabs folder and click on the Laser prefab to view the properties:image

Now, in the top you can see the tag property.

image

Click “Add Tag…”

In the Tag Manager, add the following two tags:
image

Now, click the Laser prefab again from the Prefabs folder and change the tag to Laser.
image
image

Do the same for SpaceInvader my clicking it and changing the Tag property to Enemy.

image

First, we need to add a collider to our laser prefab and our enemies. We can ue a bounding box that defines the collision range of our objects. Go to the Prefabs folder, click the Laser prefab and click Add Components in the property view:

image

Search for “box” and click on the BoxCollider.
image

This will add a Box Collider component to the prefab.

If we drag the prefab to the scene now, we can see in the Scene view that the object now contains a green box around it.

image

Click on the Laser GameObject in the Hierarchy, and change the box colliders scale property so it got the following values:

image

This will make the bounding box more correct based on the size of the LaserBody.

Again, click the Laser prefab again and add a new component called Rigidbody.

image

Now, a Ridgidbody component is added to the Prefab – giving it physics. We don’t want to use gravity so uncheck the Use Gravity property on the Rigidbody component of the Laser prefab:

image

To apply these changes to our Prefab object, click the Laser GameObject that we just changed to view the properties, and click “apply”:
image

This will save the changes we did with to the prefab.

Let’s do the same for our SpaceInvader prefab:
image

This box collider will be perfect since the default size is 1,1,1 on the box, and the size of the enemy is also 1,1 (X,Y).

Also here, add a Rigidbody component and uncheck the Use Gravity checkbox.

Now, while having a tag, a box collider and a rigdibody component to the prefabs, we can handle collisions between them.

Scripting the collision

Let’s edit the EnemyController script so it can handle collisions. First of all, if there is a collision between a laser and an enemy, we just want to remove them from the game.

Unity comes with a function on all GameObjects called OnCollisionEnter() that will trigger when a collision between this object and an other object happen. Let’s add this to our script:

using UnityEngine;
using System.Collections;

public class EnemyController : MonoBehaviour {
    public float speed;
    // Use this for initialization
    void Start () {
    }

    void OnCollisionEnter(Collision collision)
    {
    }

    // Update is called once per frame
    void Update () {
        this.transform.position -= new Vector3(speed, 0, 0) * Time.deltaTime;
    }
}

Now, we need to just handle the collision between this object (tagged “Enemy”) and objects tagged with “Laser”, and if this is the case – destroy both:

using UnityEngine;
using System.Collections;

public class EnemyController : MonoBehaviour {
    public float speed;
    // Use this for initialization
    void Start () {
    }

    void OnCollisionEnter(Collision other)
    {
       
if (other.gameObject.tag.Equals(“Laser”))
        {
            Destroy(other.gameObject);
            Destroy(this.gameObject);
        }

    }

    // Update is called once per frame
    void Update () {
        this.transform.position -= new Vector3(speed, 0, 0) * Time.deltaTime;
    }
}

Simple right? Smilefjes

Now, what happens to the lasers that miss an invader? It continues to fly forever. Let’s fix this as well. Open the LaserController script and add the following if-statement to the Update() function:

using UnityEngine;
using System.Collections;

public class LaserController : MonoBehaviour {

    // Use this for initialization
    void Start () {
   
    }
   
    // Update is called once per frame
    void Update () {
        this.transform.position += new Vector3(10, 0, 0) * Time.deltaTime;

        if (this.transform.position.x > 20.0f)
        {
            Destroy(this.gameObject);
        }

    }
}

Adding the explosion

There isn’s much fun without the explosions! Let’s add a GameObject to the EnemyController script. Edit the EnemyController script so it includes a GameObject for the explosion prefab, and then instansiate if in the OnCollisionEnter function:

using UnityEngine;
using System.Collections;

public class EnemyController : MonoBehaviour {
    public float speed;
    public GameObject explosion;
    // Use this for initialization
    void Start () {
    }

    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag.Equals(“Laser”))
        {
            Destroy(other.gameObject);
            Destroy(this.gameObject);
            Instantiate(explosion, this.transform.position, this.transform.rotation);
        }
    }

    // Update is called once per frame
    void Update () {
        this.transform.position -= new Vector3(speed, 0, 0) * Time.deltaTime;
    }
}

Now, we must set the explosion GameObject variable. This is done in Unity (as you might remember). Go to the Prefabs folder and click the SpaceInvader prefab so view the properties. Now, go to the Particles folder in the Standard Assets folder, then Legacy Particles and drag the explosion prefab to the Explosion property of the Enemy Controller Script Component of SpaceInvader prefab:

image

Press play again, and shoot a SpaceInvader, and you will see the explosion!
image

Game Over?

If an invader survives and manages to fly to the left side of the screen, it’s game over and we will be brought to a Game Over screen.

First of all, we need to create the Game Over scene. Click File->New Scene and a new scene is added to the project. Save the scene to the Scenes folder named gameOver.

Now, just to keep things simple, add a GUI Text Game Component to the scene:

image

And change the properties like this:

image

Also, change the Main Cameras properties so the background color is black:

image

Now, we need to add the scenes we have build to the project so they can find eachother.  Open the gameScene by double clicking it in the Scenes folder. Then Click File->Build Settings:

image

And then click Add Current to add the gameScene, notice it got an ID of 0:

image

Let’s also add the Game Over Scene the same way. Open the game over scene and add it:

image

Now, go to the EnemyController script:

 

using UnityEngine;
using System.Collections;

public class EnemyController : MonoBehaviour {
    public float speed;
    public GameObject explosion;
    // Use this for initialization
    void Start () {
    }

    void OnCollisionEnter(Collision other)
    {
        if (other.gameObject.tag.Equals(“Laser”))
        {
            Destroy(other.gameObject);
            Destroy(this.gameObject);
            Instantiate(explosion, this.transform.position, this.transform.rotation);
        }
    }

    // Update is called once per frame
    void Update () {
        this.transform.position -= new Vector3(speed, 0, 0) * Time.deltaTime;

        if (this.transform.position.x <= -10.0f)
        {
            GameOver();
        }
    }

    void GameOver()
    {
        Application.LoadLevel(1);
    }

}

We create a function that is called if an enemy hits the left side of the screen and Load the Game Over level that got the ID of 1.


 

Restarting the game when it’s Game Over

When the game over screen is visible, we want to restart the game so the player can try again. Here, we can just display the scene for 5 seconds and then restart the game level again.

To do this, create a new script called GameOverController and put it on the Main Camera in the gameOver scene.

Edit the GameOverController script and make it like this:

using UnityEngine;
using System.Collections;

public class GameOverController : MonoBehaviour {
    float gameOverTimer;
    // Use this for initialization
    void Start () {
        gameOverTimer = 5.0f;
    }
   
    // Update is called once per frame
    void Update () {
        gameOverTimer -= Time.deltaTime;
        if(gameOverTimer <= 0.0f)
            Application.LoadLevel(0);
   
    }
}

Nothing new here, we just change the scene after 5 seconds.

Now, run the game and you will see the game working as it should!

Are you able to add a main menu too? Smilefjes som blunker

In a later tutorial we will add SFX, Audio, UI and highscore.

Download the project and assets here:
http://sdrv.ms/19KfIUa

This entry was posted in Uncategorized. Bookmark the permalink.

38 Responses to Unity for Windows: I – Getting started

  1. Pingback: Unity for Windows: II – Publishing to Windows 8 | digitalerr0r

  2. Pingback: Unity for Windows: III–Publishing to Windows Phone Store | digitalerr0r

  3. Pingback: Unity: Free Add on for Windows 8 | Start Learning Presentation/Tutorials | Over $100,000 Contest - Dr. Doris Chen's Blog - Site Home - MSDN Blogs

  4. dant says:

    Great info. Very helpful. thanks!

  5. Martin says:

    Hi. Just started following this. Many thanks. I am totally new to Unity. I have Free version 4.1.5f1 installed. I cannot find a GameObject called a “Quad” so I am stuck. 😦

  6. dant says:

    Hi, I’m trying to find information on integrating ads or in game purchases with Win8 unity games. Do you have any pointers on that?
    Thanks!

  7. Matt Herb says:

    best tutorial ever for me regarding getting started with unity.. you held my hand like a child and I almost made it through (some trouble with the ‘other’ in the script)

    • digitalerr0r says:

      Thanks for the feedback, what “other” do you mean – in case I can fix it!

      Thanks!

      • rsampson says:

        I think he was talking about when you create the OnCollissionEnter stub.
        void OnCollisionEnter(Collision collision)
        {
        }
        When you actually code it you changed the variable to other (i.e. void OnCollisionEnter(Collission other). Thank you for the great tutorial, I will now see if my son can follow along.

  8. Pingback: Unity for Windows IV–Creating UI and saving the highscore | digitalerr0r

  9. Camilla Knutsen says:

    Thank you for an awesome tutorial!! You helped me make my first game 😀 Very good explanation, now Im going to try to see if I can do it on my own!

  10. Pingback: Unity for Windows VI–Creating a more advanced game, Part 1 | digitalerr0r

  11. Pingback: Unity for Windows: I – Getting started | digitalerr0r | Ra Puke Moana

  12. LuckyGeorge says:

    Thank you – this tutorial is great! I thought i am a fairly experienced developer but as i opened unity for the first time i had no idea what and where to do (in german one would say “Stand wie der Ochs vorm Berg.”). Now i have a slight idea of how unity works.

  13. Fantastic tutorial! I didn’t even think about using Unity before this, but it just seems so easy. I will read your other tutorials related to Unity now for sure 😀

  14. Frank Kristiansen says:

    This was great fun, and an excellent tutorial. I had some problems with just copy/pasting the scripts (might be a NOR keyboard issue) – other than that everything worked great.

  15. Great walk through!

    Now, I am playing the game and noticing that the explosions remain sitting on the screen indefinitely.

    I am trying to figure out how to set a time-out or something for these explosions, so they go away after a few seconds.

    Any suggestions?

  16. Mohsin says:

    I’m unable to find the particles package. can you link to it?

  17. Pingback: Jason Fox | Roundup of Unity tutorials and resources

  18. Pingback: Tutorials: How to Build and Port Unity Games to Windows Store and Windows Phone? - Dr. Doris Chen's Blog - Site Home - MSDN Blogs

  19. markkuhautamaki says:

    Hi. When I import and use the SpaceInvader.png texture, Unity shows only part of it. Any idea what causes this and how to fix the problem?

  20. Jatin Arora says:

    Superb tutorial, helped me a lot to get used to Unity.

  21. Very much appreciate your tutorial; it’s been a great help in learning to work with Unity.

  22. NAMAN MARRIA says:

    will anyone explain me how to dollow thos step i m stuck here

    Now, we will add a material that will be the texture of the invader. Create a new material in the Materials folder and name it spaceInvader. Drag the SpaceInvader.png file from the textures folder to the texture property of the material and change the shader to Mobile->Transparent->Vertex Color

  23. Pingback: Top 5 Intro to Unity Learning Resources - Nathalie's Blog - Site Home - MSDN Blogs

  24. Pingback: Programowanie gier mobilnych – Lab 2 | Materiały dla studentów PWSZ

  25. Pingback: Programowanie gier mobilnych – Lab 3 | Materiały dla studentów PWSZ

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.