Menu
CoddyTech

Prefabs and Instantiate

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 48 of 67.

A prefab is a GameObject saved as a template: drag an object from the Hierarchy into the Project window, and Unity stores it with all its components and Inspector values. The prefab itself is not in the scene. A script gets one through a field, like any other reference: declare public GameObject parcelPrefab; and drag the prefab onto that field in the Inspector.

Instantiate(prefab, position, rotation) builds a copy of the prefab in the scene and returns it. This delivery drone drops a parcel at its own position each time Space is pressed. Quaternion.identity means no rotation:

public GameObject parcelPrefab;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        Instantiate(parcelPrefab, transform.position, Quaternion.identity);
    }
}

Every press adds one more object to the Hierarchy, named Parcel(Clone). The prefab stays as it was, so every copy starts from the same values. GetKeyDown matters here: with GetKey, holding Space for half a second would drop about 30 parcels, one per frame.

challenge icon

Challenge

Medium

The arrows already move the player. Make each click spawn a coin above it:

  • Add a public GameObject field named coinPrefab. The scene puts the Coin prefab in it as soon as the field exists.
  • When the left mouse button is clicked, spawn one copy of the coin 2 units above the player, with no rotation.

Press Play, move and click a few times, then Check.

Try it yourself

using UnityEngine;

public class CoinDropper : MonoBehaviour
{
    public float speed = 4f;
    // coinPrefab: a public GameObject field, filled with the Coin prefab

    void Update()
    {
        if (Input.GetKey(KeyCode.RightArrow))
        {
            transform.position += new Vector3(speed * Time.deltaTime, 0, 0);
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            transform.position -= new Vector3(speed * Time.deltaTime, 0, 0);
        }

        // Click: spawn a coin 2 units above the player
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics