Coins and prefabs
The basic coin functionality is now created, but the scene needs more than one coin. The problem with simply duplicating a coin and scattering the duplicates is that if we make a change later to one coin and need to propagate that change to all other coins, we'd need to delete the former duplicates and manually replace those with newer and amended duplicates. To avoid this tedious repetition, we can use prefabs. Prefabs let you convert an object in the scene to Assets
in the Project panel. This can be instantiated in the scene as frequently as needed, as though it were a mesh asset. The advantage is that changes made to the asset are automatically applied to all instances automatically, even across multiple scenes.
This makes it easier to work with custom assets, so let's prefab the coin right now. To do this, select the Coin
object in the scene and then drag and drop it in the Project panel. When this happens, a new prefab
is created. The object in the scene is automatically updated to be an instance of prefab
. This means that if the asset is deleted from the Project
panel, the instance will become invalidated. See Figure 2.22:
Figure 2.22: Creating a coin prefab
After prefab
is created, you can add more instances of the coin easily to the level by dragging and dropping prefab
from the Project panel to the Scene. Each instance is linked to the original prefab
asset, which means that all changes made to the asset will immediately be made to all instances. With this in mind, go ahead now and add as many Coin
prefabs to the level as suitable for your coin collection game. Refer to the following figure for my arrangement:
Figure 2.23: Adding coin prefabs to the level
One question that naturally arises is how you can transform prefab back into an independent GameObject
that is no longer connected to the prefab
asset. This is useful to do if you want some objects to be based on prefab
but deviate from it slightly. To achieve this, select a prefab
instance in the Scene, and then navigate to GameObject | Break Prefab Instance from the application menu. See Figure 2.24:
Figure 2.24: Breaking the prefab instance
Note
If you add a prefab
instance to Scene and make changes to it that you like and want to distribute upstream back to the prefab
asset, then select the object and choose GameObject | Apply Changes to Prefab.