Menu
CoddyTech

Prefabs and Instantiate

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 62 of 85.

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

Make each click spawn a coin above the player.

  1. Add the field public GameObject coinPrefab;. The scene fills it with the Coin prefab.
  2. In Update(), on Input.GetMouseButtonDown(0), call Instantiate(coinPrefab, transform.position + new Vector3(0, 2, 0), Quaternion.identity);.

Press Play, move and click: a coin appears above the player each time. 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
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground