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
MediumThe arrows already move the player. Make each click spawn a coin above it:
- Add a public
GameObjectfield namedcoinPrefab. 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
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon6GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch9Prefabs and Spawning
Prefabs and InstantiateSpawn on a TimerSpawn in a GridLists of ObjectsDestroyRandom SpawnsRecap: Fireworks