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
MediumMake each click spawn a coin above the player.
- Add the field
public GameObject coinPrefab;. The scene fills it with the Coin prefab. - In
Update(), onInput.GetMouseButtonDown(0), callInstantiate(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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch11Prefabs and Spawning
Prefabs and InstantiateSpawn on a TimerSpawn in a GridLists of ObjectsTake Back the NewestDestroyRandom SpawnsRecap: Fireworks6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground