Have you ever heard about Unity Instantiate?
It’s not an interrogation, don’t worry.
But we need to understand what it’s about, because I’m pretty sure it would be great knowledge to gain.
My source told me we will cover many cool features like object cloning, projectiles and objects replacement!
But we’ll see, ready for the case partner?
What is Unity Instantiate?
Unity instantiate is a powerful method which allows us to create an instance (make a copy) of any Object types in Unity. Object is the base class for all objects Unity can reference.
So if you need prefabs, or any kind of objects we want to add to our game run time at a certain time this is the method for you.
Basically you can use it in a variety of different situations but the most common are these like the official documentation suggests:
- Object Cloning
- Build a structure
- Instantiating Projectiles
- Object Replacement
You are very lucky because today Mr.Tips our incredible mascot has the last exams to become an agent in the field to solve the cases behind game development. So later on, I will show you an example for each situation through Mr. Tips exam , so that you can better understand the power of this method.
Instantiate Methods
Let’s have a look at the method. There are different overloads of this method:
public static Object Instantiate(Object original); public static Object Instantiate(Object original, Transform parent); public static Object Instantiate(Object original, Transform parent, bool instantiateInWorldSpace); public static Object Instantiate(Object original, Vector3 position, Quaternion rotation); public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
As you can see it’s quite easy to use it. You should have noticed that the first parameter is mandatory and it’s an Object class, it means you can pass any kind of class in Unity which inherits from it. Transform, RigidBody, GameObject and basically all the classes in Unity.
Let’s look closely at the parameters:
- Origin: As we discussed before it’s an existing object you would like to instantiate
- Position: Position of the new object.
- Rotation: Orientation of the new object.
- Parent: Parent assigned to the new object.
- instantiateInWorldSpace: When you assign a parent Object, pass true to position the new object directly in world space. Pass false to set the Object’s position relative to its new parent.
Now we have seen all the important features offered by Unity instantiate it’s time to see it in action. The next chapters will be use cases of the method.
Object Cloning
The first important usage is the object cloning. What does it mean? Let me tell you an example. Mr.Tips in his exam should destroy different stakes, so in the exam room there will be 5 of these stakes to be destroyed. They should be placed one by one with a space of 2 points like the figure below.
To create this we just need to use the following snippet to our LevelManager or wherever you manage the objects positioning of your level.
public class LevelManager : MonoBehaviour { //Original object to be cloned public GameObject stake; // Start is called before the first frame update void Start() { //Create other 4 stakes for (int i = 1; i < 5; i++) { //Get the offset from the first stake float offset = 2f * (float)i; //Get the new position of the next stake Vector3 position = new Vector3(stake.transform.position.x + offset, stake.transform.position.y, stake.transform.position.z); //Cloning the first stake with the new position Instantiate(stake, position, stake.transform.rotation); } } }
Then simply add the first or better the Original object in the scene wherever you want and don’t forget to assign it to the snippet just created.
Build a structure
Now we know the power of the object cloning, we can use it for great purposes. For instance, we can build an entire game level using this guide. Or we can build a structure.. Let’s complete the training room structure of Mr.Tips to let him start his final exam by adding a final stake placed above a pyramid. We just need to add the first brick of the pyramid like this
Now we’re going to build a pyramid with the magic of Unity Instantiate.
//Original stake to be cloned public GameObject stake; //Original brick to be cloned public GameObject brick; // Start is called before the first frame update void Start() { //Create other 4 stakes for (int i = 1; i < 5; i++) { //Get the offset from the first stake float offset = 2f * (float)i; //Get the new position of the next stake Vector3 position = new Vector3(stake.transform.position.x + offset, stake.transform.position.y, stake.transform.position.z); //Cloning the first stake with the new position Instantiate(stake, position, stake.transform.rotation); } //Create the brick piramid for (int i = 1; i < 14; i++) { //Build as piramid till half if (i <= 7) { for (int j = 0; j < i; j++) { //Get the x offset from the first brick float offset = brick.GetComponent().bounds.size.x * (float)i; //Get the y offset from the first brick float verticalOffset = brick.GetComponent().bounds.size.y * (float)j; //Get the new position of the next brick Vector3 position = new Vector3(brick.transform.position.x + offset, brick.transform.position.y + verticalOffset, brick.transform.position.z); //Cloning the first brick with the new position Instantiate(brick, position, brick.transform.rotation); } //Now build as wall } else { for (int j = 0; j < 7; j++) { //Get the x offset from the first brick float offset = brick.GetComponent().bounds.size.x * (float)i; //Get the y offset from the first brick float verticalOffset = brick.GetComponent().bounds.size.y * (float)j; //Get the new position of the next brick Vector3 position = new Vector3(brick.transform.position.x + offset, brick.transform.position.y + verticalOffset, brick.transform.position.z); //Cloning the first brick with the new position Instantiate(brick, position, brick.transform.rotation); //Place a last stake in the top of our beautiful piramid if (i == 13 && j == 6) { //Get the last stake position Vector3 lastStakePosition = new Vector3(brick.transform.position.x + offset, brick.transform.position.y + verticalOffset + (stake.GetComponent().bounds.size.y/2f) + (brick.GetComponent().bounds.size.y/2f), brick.transform.position.z); //Cloning the first stake with the new position Instantiate(stake, lastStakePosition, stake.transform.rotation); } } } } }
Let’s have a look at the final result.
Great! Now the training room is completed and Mr.Tips can do his final exam!
Instantiating projectiles
Everyone dreamt about creating a shooter game once. Unity instantiate helps us to create projectiles. It’s very similar to the previous chapter, but this time let’s increase the difficulty instantiating prefabs instead of cloning objects already in the scene. This is extremely useful because we don’t have a bullet in the scene before the player shot.
First of all we need to save our bullet prefab in our “Resources” folder. If you don’t have it simply create it inside the “Assets” folder.
Now let’s see the snippet to instantiate a prefab.
//An empty object which handles the start position of a bullet public Transform bulletSpawn; //The Unity Object reference to the bullet private Object bulletRef; // Start is called before the first frame update void Start() { //Load the reference from Resources to be ready to instantiate it //"Prefabs" is a sub-folder of "Resources" //"bullet" is the name of the Prefab bulletRef = Resources.Load("Prefabs/bullet"); } // Update is called once per frame void Update() { //Pressing Fire button if (Input.GetKeyDown("Fire 1")) { //Instantiate a new bullet in the position and rotation of the placeholder object for the start position GameObject bullet = (GameObject)Instantiate(bulletRef, bulletSpawn.position, bulletSpawn.rotation); } }
Now we can give to Mr.Tips the power to destroy all the stakes. Let’s see it in action.
Wow! Mr.Tips has just become a war machine!
Object Replacement
Once a bullet hits something it could be very cool to see an explosion or something that simulates the collision. Oh, and by the way, we did great research about collisions and colliders in Unity Collision Detection 2D Everything You Need To Know + Examples Well Unity Instantiate helps us in this case too, amazing right?
Let’s see an hypothetical bullet class
public class Bullet : MonoBehaviour { //Bullet Spped public float speed = 20f; //The bullet RigidBody private Rigidbody2D rigidBody; //Explion Ref private Object explosionRef; // Start is called before the first frame update void Start() { //Get the bullet rigidbody component rigidBody = GetComponent(); //Load the reference from Resources to be ready to instantiate it //"Prefabs" is a sub-folder of "Resources" //"bullet" is the name of the Prefab explosionRef = Resources.Load("bullethit"); } // Update is called once per frame void FixedUpdate() { //Set the velocity of the bullet rigidBody.velocity = transform.right * speed; } private void OnTriggerEnter2D(Collider2D collision) { //Instantiate an explosion object at the actual position of the bullet GameObject explosion = (GameObject)Instantiate(explosionRef, transform.position, transform.rotation); //Destroy the bullet Destroy(gameObject); } }
The important part is the one inside the OnTriggerEnter2D method, once the bullet collides with something it instantiates an object explosion and then it destroys itself.
Let’s see it in action:
Wow it seems everything it’s ready for Mr.Tips final exam.
Mr.Tips final exam
Finally it’s time to see Mr.Tips in action, let see if he will be able to pass his exam and become a real agent of game development.
Conclusions
Today we can enjoy two special events. First we discovered the secrets behind Unity instantiate and second Mr.Tips became an agent.
Keep in mind that Unity instantiate allows us to create clones of any objects in Unity and we can use it for many purposes like:
- Clone objects
- Build structures
- Clone Prefabs
- Instantiate projectiles
- Replace objects
You are the best partner I have ever had without your help Mr.Tips would never have passed his exam and to say thank you he wants to share with you his winning pose.