noobtuts

Unity Prefabs

Foreword

This short article explains what Unity's Prefabs are and what they are useful for.

Motivation

Let's imagine that we want to make a Tower Defense game in Unity. At first we would create a Tower GameObject, that would look something like this in the Hierarchy:
unity-hierarchy

When the player starts the game, usually there are no Towers in the scene yet. What we need is a way to save our Tower GameObjects somewhere and then load them into the Hierarchy again as soon as the player wants to build a tower.

This is what Prefabs are for.

Creating a Prefab

Let's create a Prefab. It's very easy, all we have to do is drag our GameObject from the Hierarchy into the Project area like this:
unity-create-prefab

Afterwards we can see the Prefab in our Project area:
unity-prefab

Now we can delete the GameObject from our Hierarchy so it's not in the game world anymore. But since it's in the Project area, we don't lose it completely.

Loading a Prefab

If we want to load a prefab, we have two options. We can either do it manually by dragging it from the Project area into the Hierarchy area, or by using a script that calls Instantiate.

Here is an example script that loads a Prefab as soon as the game starts:

using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {
    public GameObject prefab = null;
               
    void Start () {
        // instantiate the prefab
        // -> transform.position means that it will be
        //    instantiated at the position of *this*
        //    gameobject
        // -> quaternion.identity means that it will
        //    have the default rotation, hence its not
        //    rotated in any weird way
        Instantiate(prefab,
                    transform.position,
                    Quaternion.identity);
    }
}

Now all we have to do is add the Test script to a GameObject in the scene, take a look at the Inspector and then set the public prefab variable to any Prefab from our Project area like this:
unity-instantiate-prefab

After pressing start, it immediately loads our Tower Prefab into the scene.

Simple as that!