Unity – Prefabs – Pre Configurated GameObjects

Unity Prefabs are pre-configurated GameObjects

Essentials

– A Prefab is a type of asset (attività), a reusable GameObject stored in Project View.

– Prefabs can be inserted into any number of scenes, multiple times per scene.

– When you add a Prefab to a scene, you create an instance of it.

– All Prefab instances are linked to the original Prefab and are essentially clones of it. No matter how many instances exist in your project, when you make any changes to the Prefab you will see the change applied to all instances.

Creating Prefabs

In order to create a Prefab, simply drag a GameObject that you’ve created in the scene into the Project View.

1. Assets> Import New Asset… (Importa una nuova attività)> file.fbx (3D Model)

2. Assets> DRAG the imported Asset in the ‘Scene’ window twice
NOTICE: Hierarchy> The GameObject’s name will turn blue to show that it is a Prefab.

OR

DRAG AND DROP the Asset inside ‘Prefab’ folder

3a. Assets> select the imported Asset> Change material, ALL GameObjects in the scene will change.
OR
3b.Hierarchy> select a GameObject> Change material, ALL GameObjects in the scene will change.

After you have performed these steps, the GameObject and all its children have been copied into the Prefab data. The Prefab can now be re-used in multiple instances. The original GameObject in the Hierarchy has now become an instance of the Prefab.

Inheritance

Inheritance means that whenever the source Prefab changes, those changes are applied to all linked GameObjects. For example, if you add a new script to a Prefab, all of the linked GameObjects will instantly contain the script as well. However, it is possible to change the properties of a single instance while keeping the link intact. Simply change any property of a prefab instance, and watch as the variable name becomes bold. The variable is now overridden. All overridden properties will not be affected by changes in the source Prefab.

– If you want to update the source Prefab and all instances with the new overridden values, you can click the Apply button in the Inspector.
Note that the root’s position and rotation will not be applied, as that affects the instances absolute position and would put all instances in the same place. However position and rotation from any children or ancestors of the root will be applied as they are computed relative to the root’s transform.

– If you want to discard all overrides on a particular instance, you can click the Revert button.