Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Prefabs
2.1.
Common Usage of Prefabs
3.
Instantiating a Prefab
3.1.
Common Scenarios
4.
Frequently Asked Questions
4.1.
What is a Prefab?
4.2.
What happens to changes that you make to a Prefab Asset?
4.3.
 
4.4.
How to create an empty GameObject?
4.5.
 
4.6.
What is the advantage of nesting Prefabs?
5.
Conclusion
Last Updated: Mar 27, 2024

Prefabs and Instantiation

Introduction

Prefabs come in handy when you need to instantiate a complex GameObject or a set of GameObjects at runtime. Compared to generating GameObjects from the start using code, instantiating prefabs with code is superior and offers several advantages.

During gameplay, instantiating and destroying objects is quite crucial. Instantiating implies bringing something into being. Items "spawn" in the game, adversaries die, GUI components disappear, and sceneries are loaded. Knowing how to effectively get rid of unnecessary stuff and bring in those you do becomes even more important.

Prefabs

The Prefab system in Unity allows you to build, configure, and save a GameObject as a reusable Asset, replete with its components, property values, and child GameObjects. The Prefab Asset serves as a template for creating new Prefab instances in the Scene. Converting a GameObject set in a certain way, such as a non-player character (NPC), prop, or piece of scenery, to a Prefab allows you to reuse it in numerous places in your Scene or across several Scenes in your Project. This is preferable just to copy and paste the GameObject since the Prefab system automatically keeps all copies in sync.

Source: Unitydocs

Any changes you make to a Prefab Asset are instantly mirrored in all instances of that Prefab, allowing you to make broad changes throughout your whole project without having to make the identical changes to every copy of the Asset. Prefabs may be nested inside other Prefabs to construct complicated object hierarchies that are straightforward to change at numerous levels.

This does not imply that all Prefab instances must be similar. If you want certain Prefab instances to be different from others, you may override settings on specific prefab instances. You may also construct Prefab variations, which allow you to organize a collection of overrides into a meaningful version of a Prefab. They are handy when you wish to instantiate GameObjects during runtime that did not exist in your Scene at the start, such as when you want powerups, special effects, projectiles, or NPCs to emerge at the appropriate points throughout gameplay.

Common Usage of Prefabs

Some common use cases of prefabs include:

1. Environmental assets - A particular variety of trees utilized several times around a level.

2. Non-player characters (NPCs) - A specific type of robot may appear several times in your game over various levels. They can differ in their movement speed or sound (through overrides).

3. Projectiles - Such as a pirate's cannon may create a cannonball Prefab every time it is fired.

4. The player's main character -  The player's prefab might be put at the beginning of each level (different Scenes) in your game.

Instantiating a Prefab

Your code requires a reference to a Prefab to instantiate it at run time. You may make this reference by storing the Prefab reference in a public variable in your code. In the Inspector, the public variable in your code shows as an assignable field. You can then select the actual Prefab you wish to utilize in the Inspector.

The script sample below includes a single public variable, "myPrefab" a Prefab reference. The Start() function creates an instance of that Prefab, using UnityEngine:

public class InstantiationExample: MonoBehaviour 
{
    public GameObject myPrefab;
    void Start()
    {
        Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity);
    }
}

 

To use this:

1. In your Project, create a new C# script called "InstantiationExample".

2. Copy and paste the preceding script example into your new script, then save it.

3. Using the GameObject > Create Empty menu, create an empty GameObject.

4. Drag the script onto the empty GameObject to add it as a component to the new GameObject.

5. Create any Prefab and drag it from the Project window into the script component's My Prefab field.

Source: Unitydocs

When you enter Play Mode, you will see your Prefab appear in the Scene at (0, 0, 0). You may change which Prefab is instantiated by dragging a different Prefab into the My Prefab field in the Inspector without changing the script.

Common Scenarios

To demonstrate the power of instantiating Prefabs at runtime, here are some scenarios:

1. Building a structure from a single Prefab by reproducing it several times in different places, such as a grid or circular.

2. A projectile Prefab is fired from a launcher. The projectile Prefab might have a Mesh, Solid body, Collider, Audio source, Dynamic Light, or a child GameObject its trail Particle System.

3. A vehicle, structure, or figure, such as a robot, disintegrates into several fragments. The sample script deletes and replaces the whole operating robot Prefab with a destroyed robot Prefab in this case. This wrecked Prefab comprises individual broken robot components with its Rigidbodies and Particle Systems. With just one line of code that substitutes the original GameObject with a damaged Prefab, you can blow up a robot into several pieces.

Frequently Asked Questions

What is a Prefab?

Prefabs are copies of GameObjects that may be replicated and placed in a scene even if the GameObject did not exist when the scene was created.

 

What happens to changes that you make to a Prefab Asset?

All the changes you make to a Prefab Asset are instantly mirrored in all instances of that Prefab, allowing you to make broad changes throughout your whole project without making identical changes to every copy of the Asset.

 

How to create an empty GameObject?

Using the GameObject > Create Empty menu, we can create an empty GameObject.

 

What is the advantage of nesting Prefabs?

Prefabs can be nested inside other Prefabs to construct complicated object hierarchies that are straightforward to change at numerous levels.

Conclusion

This article extensively discussed the Prefabs system and Instantiation in Unity in this article. We start with a brief introduction of the Prefabs, its use cases and then move on to the Prefabs Instantiation.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive Programming, JavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problems, interview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass