• $19 Game Dev' Courses - Use code "FEBUDEMY"

    Video courses

Learn to Code by Making Games – The Complete Unity Developer

Build 7 2D & 3D games

Become a Game Developer/Designer: Complete Master Series

Massive 70 hour course!

Make VR Games in Unity with C# for multiple headsets

Google Cardboard, Oculus Rift and more.

In this project we will begin to see the power of C# classes as reusable templates for objects. We will create a simple character sprite and then learn how to detect mouse-clicks to spawn as many duplicates/clones of the object as we like.

unity-game-development-books-728-90

Please visit the Unity category of the Game Code School bookstore

About this project

Skill level 1
Time to complete 30 minutes

New concepts

  1. Detecting and responding to mouse clicks
  2. Spawning new game objects
  3. Converting screen coordinates to world coordinates
  4. Learn that we should destroy objects as well

First we need to create a new Unity project. Call it Spawning Objects and be sure to select the 2D option.

Download the bob.png graphic below by right-clicking it and selecting Save image as… In Unity add Bob to the project by right-clicking in the Project window and selecting Import New Asset…

Download the bob graphic

Say hi to Bob

Drag bob from the Project window to the Hierarchy window to create a new game object. The Scene window should now look like this.

The scene window after dragging Bob to the Hierarchy window

The scene window after dragging Bob to the Hierarchy window

Left click bob in the Hierarchy window to bring up the details in the Inspector window. Click the Add Component button and select Physics 2D | Rigidbody 2D . You can run the game and Bob will fall into oblivion, off the bottom of the screen. What we want to do now is control how we spawn instances of this game object.

Why we need to spawn new game objects(clones)

Suppose we had a zombie game, we would probably want to regularly spawn zombies. If we had a player with a gun we would need to be able to spawn bullet objects. A question for both of the previous scenarios is when do we want to spawn the objects. The answer for both the previous scenarios is different. The zombies might need to be spawned at the beginning of a level or when a player enters a particular part of the map. A bullet might need to be spawned on a mouse click or button press. The point is, our game will need to detect and respond to events.

Events in Unity (and other game engines) are how we control the flow of our game. For the purposes of this quick tutorial and so we can learn how to spawn an almost infinite number of bob objects, we will see how to detect mouse click events.

Create a new C# script by right-clicking in the Project window and selecting Create | New C# Script. Name the script ClickHandler.

For the script to work it needs to be attached to a game object. Right-click in the Hierarchy window and select Create Empty… Rename the new game object to ClickHandler. Now, left-click the ClickHandler object in the Hierarchy window to make sure it is selected in the Inspector window. Find the ClickHandler script in the Project window and drag and drop it onto the ClickHandler object in the Inspector window.

Now you should have a new game object called ClickHandler with a component, which is a script, also called ClickHandler. The Inspector window should look like this next image.

A script on the game object in the Inspector window

A script on the game object in the Inspector window

Make these minor changes to the code:
1. Open the script by double-clicking it in the Project window.
2. Add a new GameObject called bob. Use public as the access specifier.
3. Delete the Start method because we won’t be needing it.

Now your code should look like this.

using UnityEngine;
using System.Collections;

public class ClickHandler : MonoBehaviour {

	public GameObject bob;

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

	}

}

Now we can add some more code to this script.

Detecting clicks

To detect clicks we need to add code to the Update method. This is the code that detects the left mouse button being clicked.

if (Input.GetMouseButtonDown(0))
	// Do something here

Now we can see how to spawn a new object on each click.

Spawning/instantiating new objects

Now we know how to detect a click we need to find out how to spawn a bob object and replace the // Do something here code. As well as spawning a bob on each click, it would be nice if we could spawn each new bob at the mouse pointer position. The code we will need to write is going to be a few lines long so it is a good candidate for a method.

Add this code for our SpawnBob method to the script after the final closing curly brace } of the Update method but before the closing curly brace of the ClickHandler class.

void SpawnBob(){

	// Where should we spawn Bob?
	Vector3 clickPosition =
		Camera.main.ScreenToWorldPoint(Input.mousePosition);

	clickPosition.z = 0;

	// Now we can actually spawn a bob object
	Instantiate(bob, clickPosition, Quaternion.identity);

}

This is how the previous code works. We declare a new Vector3 and initialize it using the Camera.main.ScreenToWorld method. This method converts the current mouse coordinates to the world coordinates in our game.

Explaining world and screen coordinates

If world and mouse coordinates are confusing, just consider that some (possibly most) games have a world which is larger than the screen. In addition, the game must run on screens of different sizes. It makes sense to handle all game objects using world coordinates, independent from the pixel positions of the screen. Unity handles all the math for us we just need to be aware that it is happening and occasionally (like when detecting mouse clicks) handle the situation. Furthermore, we will eventually build games with vast sprawling worlds. Clearly, using the screen pixel coordinates will quickly become insufficient.

We then set the z coordinate of screenPosition to zero because our game is 2D and has no depth. Finally, we use the Instantiate method to spawn a new bob object. The three parameters of the Instantiate method can be explained as follows.

  1. bob: The object to spawn/instantiate
  2. position: Where to spawn in the game world
  3. Quaternion.identity: Full explanation is beyond the scope of this tutorial but basically it sets all axes of rotation to zero

Tip: If you want to find out more about quaternions in the context of Unity then take a look at the Unity quaternion docs web page.

Add this next if statement to the update method which will call the new SpawnBob method, every time the mouse is clicked.

if (Input.GetMouseButtonDown (0))
	SpawnBob ();

Just to be absolutely sure that you know where to put the code we have just discussed, here is the entire contents of the ClickHandler script.

using UnityEngine;
using System.Collections;

public class ClickHandler : MonoBehaviour {

	public GameObject bob;

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

	if (Input.GetMouseButtonDown (0))
		SpawnBob ();

	}

	void SpawnBob(){

		// Where should we spawn Bob?
		Vector3 clickPosition =
			Camera.main.ScreenToWorldPoint(Input.mousePosition);

		clickPosition.z = 0;

		// Now we can actually spawn a bob object
		Instantiate(bob, clickPosition, Quaternion.identity);

	}
}

The final thing we have to do before the code will work is to let the ClickHandler script know which GameObject to use. Of course, we want to use bob. When we added the new GameObject to the script we made it public. This means we can drag bob from the Hierarchy window onto the GameObject public variable via the Inspector window. This image shows you exactly where to drag bob to.

Drag bob from the Hierarchy window to here

Drag bob from the Hierarchy window to here

And this image shows you what it looks like when you have been successful.

Your script component should look like this.

Your script component should look like this

Run the game and spawn bobs until your heart is content- almost!

Bob is part adventurer, part rabbit

Bob is part adventurer, part rabbit

But what will we do with all these Bob objects?

Destroying game objects

We have caused a problem! It is very inefficient to have lots of unnecessary objects in your game. While the game is running, take a look at the Hierarchy window which shows all the active game objects.

Loads of Bob objects drain memory and CPU cycles

Loads of Bob objects drain memory and CPU cycles

When a bob object is no longer relevant, we should get rid of it, destroy it. We can destroy an object with code that would look like this.

// destroy bob
Destroy (bob);

There is one obvious problem. Which instance of all our many bobs would this code work on? The next problem is deciding where this object destroying code should go. One possibility might be in a script that runs at the end of a level. Another might be when the object collides with another, perhaps a zombie with a shotgun blast or a bob with the bottom of the screen. We will see how to solve both these problems in the next project.

We will leave this tutorial for now because we have achieved what we set out to do. Just understand that a responsible game developer tidies up their objects when they are finished with them. The next project will look at collision events in Unity 2d and we will also do a bit of object destroying.

unity-game-development-books-728-90

Please visit the Unity category of the Game Code School bookstore