Tutorial: Prefabs - CodingDino/Dino-Unity-Toolkit GitHub Wiki

This tutorial will walk you through how to use Prefabs in your game to duplicate Game Objects and keep their settings in sync, and to spawn them into the game while the game is running.

This tutorial requires a moving player using something like the Tutorial: Platformer Player Movement, and a collectable like the one from Tutorial: Collectables.

For assets, we will be using several images from the asset website Kenney Assets (www.kenney.nl). We will be using assets from the Platformer Art: Pixel Redux for this tutorial. However, you are welcome to use your own custom assets as desired.

Creating a Prefab

To create a prefab, we must first crate a GameObject in our scene to base our Prefab on. We will be using the coin from Tutorial: Collectables for this purpose, so if you have not completed that tutorial, do so now before continuing.

Once you have your coin set up, select it in in the Hierarchy window.

To create our prefab, all we have to do is drag this object into the Project window. This will create a new file in our Assets folder with the .prefab extension. This is just a text file with all the settings for your GameObject recorded inside it. You can actually open it up with a text editor to look at the values, and can even change them in the text editor if you want to!

Once you've created this prefab file, it's best to put it into a folder for Prefabs to keep things nice and neat. Create a Prefabs folder in your Project window and move your new file there by dragging it. Keeping your Project window organised will be very important in larger projects!

You may have noticed that the name for your GameObject in the Hierarchy window has turned blue. This indicates that it is associated with a Prefab. If you select it, you will also see there is a new "Prefab" section at the top of the inspector with three buttons - "Select", "Revert", and "Apply". We'll learn about the last two later, but for now you can use the "Select" button to easily find the prefab file in your Project window that this object is tied to.

Cloning a Prefab

Now that we have created our prefab file, we can use it to clone, or duplicate, our coin. We can make many coins for our player to collect! This process is also known as "instantiating" the prefab - a single copy of the prefab in the scene is called an "instance".

Cloning the prefab is very easy - it is simply the reverse of how we created it. We just drag it into the scene - the same way we would create a GameObject from a sprite! Drag several copies of your prefab into your scene now to make a few different coins for your player to pick up.

You should see your new clones in the Hierarchy window, showing blue to indicate they are tied to the prefab file. They will automatically be given a number when there are duplicates with the same name. Click on them and assure yourself that they have the same components and settings as your original coin. Try playing the game - the player should be able to collect all the new coins as well as the first one without any additional tinkering needed!

Applying Changes to a Prefab

So far, we can do everything above a bit easier by just using copy+paste! However, we'll now see the true power of prefabs. In reality, we often don't start out making our game with all our final art completed. Or, we may change our minds on game logic or settings partway through. The reality is, we will need to make changes. With prefabs, we can make that change once and apply it to all the clones of that prefab with a single click. This saves us a lot of time and potential errors!

Let's assume for now we have decided to change the image for our coin. Click on any of the copies of the coin currently in your scene. Look at the Inspector for that copy of the coin and expand the Sprite Renderer. Drag a new sprite into the Sprite slot in the Sprite Renderer to change the look of the coin - I'll change mine to silver.

You might notice that the Sprite field has turned bold. This indicates that there is a change on this copy of your prefab that is different from the file! You can see that the selected copy's image is now the silver coin, but the other copies are still the gold coin.

To fix that, we need to simply hit one of the buttons we saw earlier at the top of the Inspector window - the "Apply" button. This will update the file for your prefab with any changes to the settings. You'll see that the Sprite field is no longer bold, and all of your other coins will also turn silver!

Sometimes, however, you may want to un-do a change and return your copy back to the settings of the master prefab file. To do that, you can use the other button at the top of the Inspector window - "Revert". Try changing one of the coins to another image (I will use a copper coin), then Reverting - the coin should change back to silver, because that is the image on the master prefab in your Project window.

Prefabs Across Scenes

These settings can even be copied, applied, and updated across scenes. Say you have one scene for Level 1, and another scene for Level 2. You probably want the same kind of coins in both levels. Since your prefab is in the Project window, you can easily drag it into either scene since this window is the same across all scenes in your game.

Try this now - create a new scene (we don't have to add the player or anything else for now). Drag a coin prefab in to your scene. Change the image on the copy in your new scene, then go back to your previous scene. You should see that all your coins have changed to the new image!

Cloning Prefabs at Runtime

One of the most useful features of prefabs is that cloning doesn't have to happen at design time - we can clone objects while the game is running as well! This is especially useful for things like monster spawners. For our example, we'll make a very simple script that clones the prefab when the game starts - you can expand this using different types of Activator components to clone the prefab under any condition you like!

Before we start, let's clearly state our goal behaviour:

Clone our coin prefab when the game starts.

Action

Our action, in this case, is the first part of this behaviour:

Clone our coin prefab...

To do this, we'll use a SpawnObjectAction. This action will duplicate a GameObject or prefab when activated, placing the new object in the same spot as the GameObject the SpawnObjectAction is attached to.

Add a new GameObject into your scene and drag it to where you want your new coin to spawn. Name your new object something like "CoinSpawner" - remember to always give objects descriptive names! Add the SpawnObjectAction component to it using the "Add Component" button in the Inspector window.

Activator

We know Actions don't just happen on their own - we need an Activator to trigger our SpawnObjectAction! Based on our stated goal behaviour above, our activator is the second part:

...when the game starts.

For this, we'll use the InitializerActivator. This activator triggers actions during the attached GameObject's start up process.

Click on your spawner and attach this new component now using the Add Component button in the Inspector window.

Now add a new entry to the Action list for the OnStart() portion of the Activator. Drag your CoinSpawner into the GameObject slot for your new Action entry, as this is where our SpawnObjectAction is located. Then choose SpawnObjectAction > ActionSpawnObject (GameObject) from the dropdown.

This will create a new field where you can drag in the GameObject that should be spawned. This can be an object from the current scene, but more often, we'll use a prefab! Drag your Coin prefab into this slot now.

Now if we run the game, we will see that when the game starts, a coin has appeared in the place where the CoinSpawner object was positioned! This may not seem very impressive (we could have just done this by placing a coin there to begin with, after all) - but, it's just the most simple example of what you can do with spawning at run time.

Here are some challenges to try:

  1. Spawn a coin every second
  2. Spawn a coin when the player presses a button
  3. Spawn random type of coin - use multiple prefabs and the RandomAction component - you will still need some other Activator to trigger it!