0
0
Unityframework~5 mins

Instantiating objects at runtime in Unity

Choose your learning style9 modes available
Introduction

Instantiating objects at runtime lets your game create new items or characters while it is running. This helps make games more dynamic and interactive.

When you want to spawn enemies during gameplay.
When creating bullets or projectiles when the player shoots.
When adding power-ups or collectibles as the game progresses.
When generating obstacles or platforms dynamically.
When duplicating objects based on player actions.
Syntax
Unity
Instantiate(originalObject, position, rotation);

originalObject is the object you want to copy (usually a prefab).

position and rotation set where and how the new object appears.

Examples
This creates a new enemy at the center of the scene with no rotation.
Unity
Instantiate(enemyPrefab, new Vector3(0, 0, 0), Quaternion.identity);
This spawns a bullet at the gun's tip, matching its direction.
Unity
Instantiate(bulletPrefab, gunTip.position, gunTip.rotation);
This creates a power-up rotated 45 degrees on the Y axis and saves it to a variable.
Unity
GameObject newPowerUp = Instantiate(powerUpPrefab, randomPosition, Quaternion.Euler(0, 45, 0));
Sample Program

This script creates a new cube object at position (1,1,1) when the game starts. The cube has no rotation and is renamed to "SpawnedCube".

Unity
using UnityEngine;

public class Spawner : MonoBehaviour
{
    public GameObject cubePrefab;

    void Start()
    {
        Vector3 spawnPosition = new Vector3(1f, 1f, 1f);
        Quaternion spawnRotation = Quaternion.identity;

        GameObject newCube = Instantiate(cubePrefab, spawnPosition, spawnRotation);
        newCube.name = "SpawnedCube";
    }
}
OutputSuccess
Important Notes

Always use prefabs for objects you want to instantiate to keep your project organized.

Remember to set the position and rotation carefully to place objects where you want them.

You can store the result of Instantiate in a variable to change or track the new object.

Summary

Instantiating creates copies of objects during the game.

Use Instantiate with an original object, position, and rotation.

Store the new object if you want to modify or control it later.