Unity Instantiate prefab tutorial (with and without code)

Unity instantiate function is used to spawn prefabs or game objects at any point in the game world. Unity requires the game object, to be a prefab or available in scene hierarchy in order to spawn them. In this post, we will see how you can spawn a new object in Unity using instantiate function and the different ways to use Unity Instantiate.

To start learning Unity from scratch, check out our comprehensive list of Unity tutorials to get started.

Unity Instantiate function

The instantiate function takes in 4 arguments and only one of them is mandatory. Here is the default syntax of Unity Instantiate

Instantiate(Object, position, rotation, parent);
  1. Object is the prefab or game object that you want to spawn. This input is mandatory.
  2. Position is the Vector3 position where you need to spawn the object. If no position is provided, the object is spawned at the location of the game object to which the instantiate function is added.
  3. Rotation is the Quaternion rotation of the spawned object. You can use Quaternion.Identity to spawn the object with zero rotation.
  4. Parent is the transform of the object that needs to be set as the parent of the spawned game object.

What is Unity prefab?

Before we jump into Unity instantiate, you must know what a prefab is?

A prefab is a game object, which has already been customized to be deployed in a game scene. For example, if you have a character in your scene, you can set the position, rotation, scale, and add other components required, and move it to the project window. You can spawn this character directly in your game at a later stage.

Any game object in which you add the required components and keep it ready in the Unity resources folder for deployment, is called a prefab in Unity.

Now let’s see, how to spawn the prefab.

Instantiating a prefab in Unity

Step1: Create a prefab in Unity

Open a new project in Unity. Create a new game object in the Hierarchy window and add the necessary components. You can create empty game objects, if you only need a script to be spawned but for this tutorial, let’s use the default Unity cube.

Drag and drop the cube from the hierarchy window to the project window. That’s it, you have your prefab. Now you can delete the game object from the hierarchy window.

Prefabs in Unity project window

Step2: Adding instantiate script to the scene

Create an empty game object. Add a new script component and call it “Instantiate_example”. Open the script in Visual studio for editing. Copy and paste the below code.

This code will instantiate a prefab at the location of the new vector 3. If you want to spawn the game object at different location, then you need to change the vector 3 value.

As we are not setting any quaternion rotation, the desired game object will spawn with zero rotation.

using UnityEngine;
using System.Collections;

public class Instantiate_example : MonoBehaviour 
{ 
  public Transform prefab;
  void Start() 
  { 
     Instantiate(prefab, new Vector3(2.0F, 0, 0), Quaternion.identity);
  } 
}
Adding new script component in the inspector window

Step3: Assign prefab or Game object to the script

Select the script object in hierarchy view. Drag and drop the prefab to the prefab variable in the inspector window.

Unity instantiate script attached to a game object

During run time, the prefab will be instantiated on to your game scene at start. Unity by default names the game object as a clone of your prefab. So, if your prefab name is “Friend Cube” then Unity will name it “Friend Cube(Clone)”.

The object may have a new look based on the parent object’s rotation and scale. If you want to instantiate the object on condition, like on press of space key or mouse clicks then you can shift the function to the Update method and use an if statement as shown in the following code example.

using UnityEngine;

public class Instantiate_Random : MonoBehaviour
{
    public Transform prefab;
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Instantiate(prefab,new Vector3(2.0F, 0, 0),Quaternion.identity);            
        }       
        
    }

}

Instantiate prefab as a child of another object

Unity instantiate function, allows you to add a parent object as the fourth input to the function. If added, the spawned game object is set as the child of the parent game object.

Here is an example script to spawn a game object as child of another.

using UnityEngine;
public class Instantiate_example : MonoBehaviour 
{ 
  public Transform prefab;
  public Transform parent;

  void Start() 
  { 
     Instantiate(prefab, new Vector3(2.0F, 0, 0), Quaternion.identity, parent);
  } 

}

Instantiate prefab in Unity by name

You can reference the prefab game object and load it from the resource folder directly using Resources.Load().

The prefab you are referencing should be inside the resource folder in the project window. This is not a good practice as its more performance extensive.

using UnityEngine;
using System.Collections;

public class Instantiate_example : MonoBehaviour 
{ 
 
  void Start() 
  { 
     Gameobject newplayer=Instantiate(Resources.Load("Player", typeof(GameObject))) as Gameobject;

  } 
}

Giving a Custom name to the Instantiated prefab

By default, any game object that is instantiated in Unity is given the name “Prefab_name(Clone)”. If you instantiate multiple copies of prefab then they will be named “Clone 1”, “Clone 2” and so on. The name of the cloned object doesn’t make any difference unless you want to access it by a custom name.

If that is the case then you can assign the instantiated prefab to a game object and then set a name to the game object.

Here is the sample code to set the name of the instantiate object to “Myobject”.

my_spawned=Instantiate(prefab,transform.position,Quaternion.identity) as GameObject;
my_spawned.name="Myobject";

Instantiating a Projectile in Unity

The only difference between instantiating a game object and instantiating a projectile is, you need to add a force to the instantiated projectile so that it will move. The best way is to create an empty object and place it where you want the projectile to spawn.

For example, if you are making a rocket projectile for a rocket launcher then you need to place this empty game object at the tip of the rocket launcher.

  • Create an Empty game object and call it “Projectile_Spawner”.
  • Add a Script to it called “SpawnProjectile”.
  • Create a projectile prefab with a Rigidbody component. We need the Rigidbody component to add force to the projectile.
  • Add the below script to instantiate the projectile and add force to it.
using UnityEngine;

public class SpawnProjectile : MonoBehaviour
{
    public GameObject projectile;
    GameObject myProjectile;
    Rigidbody rb;
    float forceMagnitude=5;

    void Start()
    {
        myProjectile=Instantiate(projectile,transform.position,Quaternion.identity) as GameObject;
        rb=myProjectile.GetComponent<Rigidbody>();
        rb.AddForce(transform.forward*forceMagnitude,ForceMode.Impulse);
        
    }

}

Assign your projectile to the script and you are ready to launch a projectile.

You can use Components for Unity Instantiate

As in the above example of projectile. To access the Rigidbody of the spawned game object, we are instantiating the prefab, assigning it to another game object and using the get component method to get the Rigidbody. Then we apply force on it.

There are is a simpler way. You can instantiate the specific component rather than the game object. This way you need not use the get component function and Unity instantiates the game object by default. This is more performance efficient than the conventional way as shown in the following example.

using UnityEngine;

public class SpawnProjectile : MonoBehaviour
{
    public Rigidbody projectile;
    Rigidbody spawnedProjectile;
    float forceMagnitude=5;

    void Start()
    {
        spawnedProjectile=Instantiate(projectile,transform.position,Quaternion.identity);
        spawnedProjectile.AddForce(transform.forward*forceMagnitude,ForceMode.Impulse);      
        
    }

}

How to Instantiate at random positions in Unity

To instantiate game objects at random positions, you need to generate random numbers and create a new vector 3 with it. We will keep the Y value fixed and randomize the X and Z values.

Let’s use Random.Range to generate these values.

using UnityEngine;

public class Instantiate_Random : MonoBehaviour
{
    [SerializeField]GameObject Unity_Instantiate_Object;
    float xPos;
    float zPos;
    float minPos=0;
    float maxPos=10;
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            xPos=Random.Range(minPos,maxPos);
            zPos=Random.Range(minPos,maxPos);
            Vector3 pos=new Vector3(xPos,0,zPos);
            Instantiate(Unity_Instantiate_Object,pos,Quaternion.identity);
            
        }
        
        
    }

}

Instantiate using visual scripting (Without code) in Unity

If you are not comfortable using code in Unity, then you can also use visual scripting to instantiate a game object. Follow the steps below to spawn a game object without code.

Create a flow graph

  1. Create a new empty object in the hierarchy window.
  2. Name it as “instantiate_graph”.
  3. Go to inspector window and click add component.
  4. Add a Script machine component.
  5. Click new to create a new graph.
  6. Name it as “instantiate_example”.

Create the logic

Unity instantiate Visual scripting logic to spawn a game object after 5 seconds of game start.

We are going to instantiate a prefab called “my_prefab” after 5 seconds of game start.

  1. Add a timer, get rotation and an instantiate game object node.
  2. Set the timer duration to 5 seconds.
  3. Connect Start event to timer start and timer completed to instantiate.
  4. Set the game object to my_prefab in the instantiate node.
  5. Get the rotation of this game object using get rotation node, and connect it as input to the rotation parameter of the instantiate node.
  6. You can change the position where you want the prefab to be instantiated in the instantiate node.

Play the game and the object should spawn after 5 seconds of game start.

When and when not to use Unity instantiate

Instantiate is really useful but when using it to spawn multiple objects can fill the memory and affect game performance. Let’s see what are the ideal conditions when you can use instantiate.

  1. Spawn single characters that stay throughout the game like the player game object.
  2. Objects that are limited in number like ammo, power-ups, etc. which are destroyed later.
  3. For effects on objects like a fire that dies down after a few seconds.

Remember to destroy the object after it’s no longer needed otherwise it will add up the game memory and cause the game to freeze. So, it’s better not to use instantiate when multiple spawn is required. In that case, you can create an object pool and make them active when required.

For example, you can add a bullet game object to the scene and set it as inactive. When the gun fires set the Vector3 position of the bullet to the front of the gun and make the bullet object active. When the bullet hits a surface then deactivate it rather than destroying it. This will reduce the memory load caused by the instantiate function. You can learn about colliders to know when to deactivate the game object.

That’s it for this tutorial, try this out and let us know if you have any questions. For the next tutorial, we learn about Camera in Unity.

Leave a Reply

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