CodeBlanks Logo Icon CodeBlanks

Spawning with Instantiate

Learn to spawn a prefab instance at runtime with Instantiate.

Creating Prefabs with Instantiate

The Instantiate method creates a copy of an object at runtime. By passing a Prefab reference to Instantiate, you can add a new GameObject to the scene. This method is commonly used to spawn enemies, projectiles, rewards, or effects.

Instantiate(objectPrefab);

Setting Position and Rotation

Overloaded versions of Instantiate allow you to specify the position and rotation of the object being created. You can use a Vector3 for the position and Quaternion.identity for the default rotation. This creates the object at the coordinates you choose.

Instantiate(objectPrefab, spawnPosition, Quaternion.identity);

Practice Spawn an Object at Runtime

Check the objectPrefab asset assigned through the Inspector in the Start method. If the asset exists, create a new instance at spawnPosition with the default rotation and print a message to the console.

Starter code

Player.cs
using UnityEngine;

public class RuntimeSpawner : MonoBehaviour
{
    public GameObject objectPrefab;
    public Vector3 spawnPosition;

    void Start()
    {
        
    }
}

Sample solution

Player.cs
using UnityEngine;

public class RuntimeSpawner : MonoBehaviour
{
    public GameObject objectPrefab;
    public Vector3 spawnPosition;

    void Start()
    {
        if (objectPrefab != null)
        {
            GameObject spawnedObject = Instantiate(objectPrefab, spawnPosition, Quaternion.identity);
            Debug.Log("Yeni nesne üretildi: " + spawnedObject.name);
        }
    }
}

Expected output

Yeni nesne üretildi: Crate

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method is used to create a new object from a Prefab asset at runtime?

  • Instantiate() Correct answer
  • DestroyImmediate()
  • GetComponent()
  • SetActive()

Explanation: Instantiate() creates a new object instance from a Prefab asset.

2 Spawn an Object at a Given Position

Question
Bir Prefab'ı belirlenen konum ve varsayılan dönüş ile üretmek için ____(objectPrefab, spawnPosition, Quaternion.identity) çağrısı kullanılır.
Answer
Bir Prefab'ı belirlenen konum ve varsayılan dönüş ile üretmek için Instantiate(objectPrefab, spawnPosition, Quaternion.identity) çağrısı kullanılır.

Explanation: Instantiate can create a Prefab instance at the specified position and rotation.

3 Match Instantiate Parameters

Term Meaning
objectPrefab Source reference of the new object
spawnPosition The position of the new object
Quaternion.identity The default rotation value
Instantiate Method creating a new object instance

All lessons in Intermediate