Unity Instantiate prefab C# tutorial for beginners

You can use Unity instantiate function to spawn prefabs or Gameobjects 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 it.

Instantiate in Unity

In this post, we will see how you can spawn objects in Unity using instantiate function in your C# script and where not to use Unity Instantiate.

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 use this character in your game at a later stage. Any game object in which you add these required components and keep it ready in the Unity resources folder for deployment is called a prefab in Unity.

Instantiating a prefab in Unity

Step1: Create a prefab in Unity

  1. Create a gameobject in the Hierarchy window and make the necessary customization.
  2. Drag and drop the gameobject to the project window.
  3. That’s it, you have your prefab. Now you can delete the gameobject from the hierarchy window.

Step2: Adding script to your scene

  1. Create an empty gameobject.
  2. Add a script component and call it “Instantiate_example” (you can give it any name of your choice).
  3. Copy and paste the code below.
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);
  } 
}

Step3: Assign prefab or Gameobject to the script

  1. Select the script object in hierarchy view.
  2. Drag and drop the prefab to the prefab variable in the inspector window.
Unity instantiate script attached to a game object

Now if you hit play, the prefab will be instantiated on to your game scene at start. Unity by default names the gameobject as a clone of your prefab. So if your prefab name is Friend Cube then Unity will name it Friend Cube(Clone).

Instantiate prefab as a child of another object

You can do this by instantiating your prefab as a Gameobject and then assigning the parent. This method can be used to instantiate an UI prefab also. You just need to make sure that the parent is inside the canvas.



using UnityEngine;
using System.Collections;

public class Instantiate_example : MonoBehaviour 
{ 
  public Transform prefab;
  void Start() 
  { 
     Gameobject childprefab=Instantiate(prefab, new Vector3(2.0F, 0, 0), Quaternion.identity) as Gameobject;
     childprefab.transform.parent = GameObject.Find("parent object").transform;
  } 
}

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. 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)”. The name of the 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

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

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 Gameobject.
  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 Gameobject 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 Gameobject.

Check out the Unity asset below for efficient use of object pooling and to improve your game’s performance.

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 instantiate projectile so that it will move. The best way is to create an empty object and place it on the corner of your main object. For example, if you 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 gameobject and call it Projectile_Spawner.

Add a Script to it called SpawnProjectile.

Create a projectile prefab with a Rigidbody component. For this example, we will be adding force to the projectile to move it. You can create any prefab depending on your game’s requirement.

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.

Unity Instantiate trick that no one teaches you

As in the above example of projectile. To access the Rigidbody of the spawned gameobject, we are instantiating the gameobject, assigning it to another gameobject 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 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.

Here is how the above projectile script can be simplified.

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 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. The random range will include the minimum value and exclude the maximum value.

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 in Unity

If you are not comfortable using scripting in Unity then you can also use visual scripting to instantiate a game object.

Creating 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.

Creating the logic

Unity instantiate Visual scripting logic

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

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

Leave a Reply

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