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…
Drag bob from the Project window to the Hierarchy window to create a new game object. The Scene window should now look like this.
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 do 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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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.
1 2 |
if (Input.GetMouseButtonDown(0)) // Do something here<br> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
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 that 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.
- bob: The object to spawn/instantiate
- position: Where to spawn in the game world
- 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.
1 2 |
if (Input.GetMouseButtonDown (0)) SpawnBob (); |
Just to be absolutely sure that you know where to put the code we have just discussed, here are the entire contents of the ClickHandler script.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
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.
And this image shows you what it looks like when you have been successful.
Run the game and spawn bobs until your heart is content- almost!
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.
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.
1 2 |
// 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.
Hey John, thanks for these tutorials. Big help so far- videos just don’t cut it for me and reading how to actually code and work unity is what works. Some of your links are broken though- such as links to Part 3 of your unity tutorials as well as this one missing a link to the next project. Thanks again!
Hi there. Thanks for commenting. I have to be honest its so long ago I can’t remember where I was up to. All the unity tutorials can be reached from this page from newest to oldest.http://gamecodeschool.com/unity-projects/
How to spawn a game object in Unity? Very simply, with a magic spell:
Close your eyes, concentrate, imagine the object you want to spawn. Shout the spell “Unityus Spawnus Objectus!” and click your fingers and watch for more details – https://www.youtube.com/watch?v=DKZEYIHU6r8
Congratulations! You are a wizard who can perform miracles. ?♂️ ?