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.