Game Development
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);
Exercise 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.
Show example solution
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);
}
}
}
Test yourself
-
Which method is used to create a new object from a Prefab asset at runtime?
- Instantiate()
- DestroyImmediate()
- GetComponent()
- SetActive()
Show answer
Instantiate() — Instantiate() creates a new object instance from a Prefab asset.
-
Spawn an Object at a Given Position
Bir Prefab'ı belirlenen konum ve varsayılan dönüş ile üretmek için ____(objectPrefab, spawnPosition, Quaternion.identity) çağrısı kullanılır.
Show 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.
-
Match Instantiate Parameters
- 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
Next lesson: Prefab Variant