In this unity 2d instantiate prefab tutorial we will be looking a number of demonstrations. Where I will show you different ways prefabs can be created and instantiated in unity.

Some of the demonstrations will be click and place. Others will be instantiating 2d game objects on the fly at run time. As well as event based from say a UI click.

We will also look at object pooling which will help with optimization of your project. First let us just go through some basic concepts.

Are you interested in spawning 3d objects? Check out this video:

Basics of game object instantiation, what is instantiation?

For the non computer science folks reading this. Instantiation is just basically creating a copy of an object or game object.

So when we instantiate a game object or unity prefab we will store that copy in memory. Once we done with it we can destroy it and it will be removed from our unity project.

What is object pooling and how does it work?

Object pooling is something we can do at run time of our game to sort of cache our objects so we can re use them.

How this would work is when we run our game the first time we will instantiate all the objects we would need. We then go and reuse those objects as needed.

So for example if we were building an infinite runner game we might have a few objects which make up our infinite floor. We would want to pool those and re use them by just moving them ahead of the player.

This just reduces constant creation and destruction of game objects.

Starting our unity 2d instantiate prefab project

Open up unity hub and create a new 2d project. Call it Unity 2d instantiate prefab tutorial.

To get started to just ease you into the concept of instantiation let’s create the most basic instantiation script you can make. To do this we first need a prefab object.

So let’s create that by adding a basic square sprite game object in our unity project. You can add that by right-clicking in the assets tab and choosing this option.

We now need to convert this to a prefab. So drag it into the hierarchy then drag it back into the assets. So it should look like this.

Then click on it in the hierarchy again and press delete so you end up with this.

First unity 2d instantiate script

Let’s create some basic code now to instantiate this square on run time.

Go over to the assets tab again and right click to create a new c# script. Call the script FirstUnityInstantiate.

Open it up in visual studio by double clicking. So for the initial script we want to achieve two things. One we want to be able to add our prefab and second we want to instantiate it.

So first we need to declare a gameobject variable. So your code in the end should look like this.

using System.Collections; using System.Collections.Generic; using UnityEngine; public class FirstUnityInstantiate : MonoBehaviour { public GameObject go; // Start is called before the first frame update void Start() { Instantiate(go); } }

Very simple at this stage. All we doing here is creating a public gameobject so we can assign the script our square and in start we instantiate it. Save this off and head back to unity.

In your scene you should have a main camera. Click on it.

The camera carries no significance to the instantiation. However the camera gets created when the project runs so we can attach our script to it to keep this tutorial simple.

Go ahead and drag your script into the inspector on the right. You should end up with this.

Now we just simply add our square to the Go slot by dragging it in there. You should end up with this.

Now just simply hit the run button and you should have your first 2d game object instantiating.

More advanced – unity instantiate prefab at position with gameobjects

Let’s now look at something a little more advanced let’s now get our object to spawn at a specific position in our game scene.

For us to achieve this we will need to store our instantiated object then modify its position.

Let’s try and spawn our square in the top right corner of our screen. We can achieve this with this code. I will explain in the section after this.

using System.Collections; using System.Collections.Generic; using UnityEngine; public class FirstUnityInstantiate : MonoBehaviour { public GameObject go; // Start is called before the first frame update void Start() { GameObject tmpObj = Instantiate(go); tmpObj.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width - 20,Screen.height- 20,10)); } }

First we assign our instantiated game object to a variable called tmpObj.

Then we use our main camera to help us convert screen coordinates to world / scene points.

So then we simply assign our position to our screen width – 20 for some margin and our height with -20 for some margin.

The value of 10 is to ensure our z position is visible within the camera view. So go ahead and save this off.

You should now end up with this when you run your project.

This is now all good and well but what use is this. Well in the next section we will look at how we can place unity 2d game objects.

With that knowledge you can build all sorts of fun games or projects.

Placing game objects with unity instantiation

This is where the fun begins. To do placing of objects we want to get mouse input and interpret that and place a new object on the screen.

So we will need to manage some type of state on our mouse clicks and then later we will look at how we can remove objects on mouse click as well.

So to get started we need to add some more code to our script.

using System.Collections; using System.Collections.Generic; using UnityEngine; public class FirstUnityInstantiate : MonoBehaviour { public GameObject go; bool canplace; bool releasedbutton; Vector3 mousePos; // Start is called before the first frame update void Start() { releasedbutton = true; canplace = false; } private void Update() { if(Input.GetMouseButtonDown(0)) { releasedbutton = false; canplace = true; mousePos = Input.mousePosition; } if(Input.GetMouseButtonUp(0)) { releasedbutton = true; canplace = false; } if(releasedbutton == false && canplace) { GameObject tmpObj = Instantiate(go); tmpObj.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 10)); canplace = false; } } }

Here first we start off with a canplace and releasedbutton state. As well as a mousePos to store our mouse position. So if canplace is enabled we can place the object.

The reason for this is to prevent us creating a bunch of objects while the mouse button is being held down.

So from there we just set our release button and can place to true and false respectively in our start method.

We now readd our update method. Where we look at 2 types of input one where the mouse button is pressed down and the other the up state.

Pro tip: When spawning a lot of game objects and instantiating prefabs in unity you want to implement object pooling. Just to restrict how much memory you use in your games.

When the mouse button is down we set the relasedbutton to false because we are pressing the button as well as enabling can place and set our current mouse position.

In the getmouseup state we just reset our variables. Then finally we check if the button has been released and we are allowed to place the object.

In the instantiate we use the mousePos x and y then we convert the screen point to world space.

Finally, we set can place to false to block the instantiation while the mouse button is down.

If you have done everything correctly you should end up with something which you can place objects like this.

That’s great but how do we now remove these objects you say. Well let’s look at that in the next section.

Removing place instantiated game objects

To make this work we need to understand overlaps. We also need to keep a reference to our game objects. So we will be introducing lists as well as bounding boxes in this part of this tutorial.

So for our setup we need to do the following. First click on your Square prefab in the assets tab.

Then on the right in the inspector click on open prefab.

Add the component box collider 2d.

We will be using this to get the bounds of the square so we know when we clicked on it.

Let’s now modify our script. Here is what it will look like.

using System.Collections; using System.Collections.Generic; using UnityEngine; public class FirstUnityInstantiate : MonoBehaviour { public GameObject go; bool canplace; bool releasedbutton; Vector3 mousePos; List<GameObject> squares; // Start is called before the first frame update void Start() { squares = new List<GameObject>(); releasedbutton = true; canplace = false; } private void Update() { mousePos = Input.mousePosition; if (Input.GetMouseButtonDown(0)) { releasedbutton = false; canplace = true; } if(Input.GetMouseButtonUp(0)) { releasedbutton = true; canplace = false; } if(Input.GetMouseButtonDown(1)) { foreach (GameObject square in squares) { BoxCollider2D col = square.GetComponent<BoxCollider2D>(); if(col.OverlapPoint(Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 10)))) { squares.Remove(square); DestroyImmediate(square); } } } if(releasedbutton == false && canplace) { GameObject tmpObj = Instantiate(go); squares.Add(tmpObj); tmpObj.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 10)); canplace = false; } } }

So some of the main changes now which has happened is. We have added a gameobject list to start storing our squares in a list.

We have added this bit of code to detect a right click on one of our objects.

if(Input.GetMouseButtonDown(1)) { foreach (GameObject square in squares) { BoxCollider2D col = square.GetComponent<BoxCollider2D>(); if(col.OverlapPoint(Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 10)))) { squares.Remove(square); DestroyImmediate(square); } } }

So here we basically look for mouse right click.

Then we loop through our squares, get their boxcollider2d then we do a check using their collider to see if it overlapts with the world point of the mouse.

We then simply remove the square from our list and destroy the game object. So go ahead and save that off.

If you have done everything right you should have something like this now.

unity 2d instantiate prefab – using click and place

That was fun right. Let’s now see how we can randomly instantiate objects on our screen using a UI button.

Using unity ui buttons to instantiate 2d game objects

For this section we want to just do some random placement on the screen. So to start off we need to add ourselves a bit of basic UI.

Head over to the hierarchy and right click and create a canvas and a button using these steps.

We want our canvas to be in view of our camera. So click on the canvas in the hierarchy and modify this option.

Then grab your camera from your hierarchy and drag it into this slot.

Next right click on your canvas and create a button.

Collapse the arrow on the button and click on text.

Then in the hierarchy modify the text to say place random.

So that is it for the UI. Let’s now look at creating a script which will be triggered by this button. So back in your assets tab right click and create a c# script.

Call it RandomPlacement.

Open that up. We going to have something very similar now to our first basic script. Here is the code.

using System.Collections; using System.Collections.Generic; using UnityEngine; public class RandomPlacement : MonoBehaviour { public GameObject go; // Start is called before the first frame update void Start() { } public void randomlyPlaceObject() { GameObject tmpObj = Instantiate(go); Vector2 bounds = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height)); float xpos = Random.Range(0, bounds.x); float ypos = Random.Range(0, bounds.y); tmpObj.transform.position = new Vector2(-xpos, -ypos); } }

So once again keeping it quite simple. We just create a randomlyPlaceObject method. We then determine our screen bounds using our main camera to convert our screen points to world points.

From here we then get random ranges and set our position to those random values.

We use the negative behind xpos and y pos because our starting position is the top right corner.

Now to connect this up to our ui is also quite simple. First thing is to drag this script onto an object. We will just add it to our canvas for now.

So follow these steps. First drag the RandomPlacement script onto the canvas like so.

Drag in our square prefab from our assets.

Then click over to our button.

On the right click on the plus button.

Drag the canvas into the None (Object) slot.

Select the function from the drop down.

Now go ahead and run your project you should now have this.

unity 2d instantiate prefab – using unity ui

Not very useful as it is, but you can quickly see how you can apply this to your game in a meaningful and useful way.

Great let’s quickly look at object pooling before we wrap up.

Unity instantiate – object pooling

Let’s disable our button for this. So go to your canvas and just uncheck this box.

For our object pooling we just want to load up some squares with different colors and then turn them on and off as time passes.

So for this we going to duplicate our square prefab twice and change their colors.

You can do this by right clicking on the Square sprite in your assets and duplicating by dragging the original square sprite in and out of the hierarchy a few times to get this.

Now let’s modify their color.

Open up the prefab for each and give it a color.

You should have something like this in your assets.

Now go ahead in your assets and create a new c# script again called ObjectPoolingExample.

Here is our code.

using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectPoolingExample : MonoBehaviour { public List<GameObject> objects; List<GameObject> pool; float timer = 0.0f; void Start() { this.pool = new List<GameObject>(); foreach(GameObject go in objects) { this.pool.Add(Instantiate(go.gameObject)); } disableAll(); } void disableAll() { foreach(GameObject go in this.pool) { go.SetActive(false); } } // Update is called once per frame void Update() { timer += Time.deltaTime; if(timer > 0.2f) { //Select random object disableAll(); int poolCount = pool.Count; int randomObjectIndex = Random.Range(0, poolCount); pool.ToArray()[randomObjectIndex].SetActive(true); timer = 0.0f; } } }

So here we now have two lists one which is list of objects and our pool.

In our start method we instantiate our pool we go and pre instantiate our square objects into our pool and we disableAll of them with a method we wrote to set them inactive.

The disableall method simply loops through the pool and disables all the objects.

Next in the update we just have a timer, we disableAll when the timer runs out and we select a random object from the pool to enable.

Go ahead and save off this code.

You will need to drag this onto our main camera like before. Use these settings and drag your 3 squares into the slots like this.

unity 2d instantiate prefab – pool list

Once that’s done and if you did everything correctly you should end up with this.

unity 2d instantiate prefab – pooling

So you now may ask what is the benefit to this. Well very simple really, we re using objects which are already created simply by enabling and disabling them.

Once you have typed out the code from this tutorial you will likely understand the concept of pooling alot better.

So that’s it for this tutorial I now move onto faq and final words.

Frequently asked questions about unity prefab instantiation

How can I instantiate a game object in unity? You first need to create a prefab of your gameobject. Then assign it in a script and then finally can instantiate your object.

How can I add object pooling for instantiation in unity? The simplest way to do this is to use a list of gameobjects. You can add a bunch of pre instantiated objects to this pool then reuse them as needed.

What does instantiate mean in unity? Basically instantiate means copy. To make a copy of a gameobject or prefab in unity. Then basically placing it in your game scene.

Last words

So that’s the end of this tutorial. I hope you found it useful. If you did please consider supporting me on skillshare by joining my course: https://skl.sh/2YhzEfe

If you prefer watching video over reading tutorials, why not subscribe to my YouTube channel over here: https://www.youtube.com/channel/UC1i4hf14VYxV14h6MsPX0Yw?sub_confirmation=1

Here are also some other tutorials you might be interested in: