How to Spawn GameObjects in Unity

Enemies, power-ups, projectiles, and more—a typical game creates dozens of entities for players to interact with. Therefore, one of the first things a Unity developer must learn is how to add objects to a scene from inside scripts. In this tutorial, I will demonstrate how to spawn GameObjects in Unity using a two step process:

  1. Pre-configure a game object template (called a “prefab“) in the Unity editor
  2. Clone the desired prefab into your scene

Creating Prefabs

To start, create a template for the object you need to spawn. This template, called a prefab, is used to specify property values, components, children, etc. for the clones you will create. Creating a prefab is simple. First, add a GameObject to the scene. Next, customize this new object using the Unity editor (for example, by configuring the renderer or adding a collider). Finally, convert the game object into a Prefab Asset by dragging it from the Hierarchy window into the Project window, as illustrated below.

Step 1: Create and Customize a GameObject

Using whatever method you prefer, add a GameObject to your scene. In this example, we are just adding a square sprite. We then customize it by changing its scale transform to (0.75, 0.75, 1) and adding a custom script to assign a random color.

Unity screenshot using the 2D Object > Sprites > Square context menu options to create a game object.

Step 2: Convert the GameObject into a Prefab

To convert your configured GameObject into a Prefab, drag it from the scene hierarchy view into your project window. This process is shown in the first image below. This creates a new Prefab Asset, and converts the scene object into a “prefab instance” (indicated by the blue cube icon in the hierarchy view). You can now create duplicates of your prefab by dragging it from the Project View into your scene, or duplicate it in scripts as described in the next section.

Spawning GameObjects from Prefabs

Injecting a Prefab into Scripts

Once you have created a prefab object, you have to get a reference to it inside your script. The simplest way to do this is to assign it via the Inspector window. Any public field can be assigned this way, such as the SquarePrefab variable in the following code snippet:

public class SpawnSquares : MonoBehaviour
{
    // This value can be assigned via the Unity editor's Inspector
    public GameObject SquarePrefab;
    
    // more script members ...
}

This field will then be an editable property for any components created from that script:

Step 2: Copy a Prefab with “Instantiate”

Once you have a prefab reference in a script, you can clone it via the Instantiate method. This method creates a new GameObject and returns a reference to it. Instantiate has several overloads, but the only required argument is a reference to the prefab you want to clone. The following script uses this method to create a new clone every time the user clicks the left mouse button.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnSquares : MonoBehaviour
{
    // This value can be assigned via the Unity editor's Inspector
    public GameObject SquarePrefab;
    
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            // get the mouse click position, in world units
            var mousePosition = Camera.main.ScreenToWorldPoint(
                Input.mousePosition
            );

            // use 'Instantiate' to clone our prefab; this 3-arg version 
            // lets us set the position and rotation for the new object
            var newSquare = Instantiate(
                SquarePrefab, 
                new Vector3(mousePosition.x, mousePosition.y, 0), 
                Quaternion.identity
            );
        }
    }
}

Summary

In this post, we explored spawning GameObjects from Unity scripts. This is accomplished by creating prefab objects (i.e. templates), and then cloning them with the Instantiate method. If this information was helpful, you may want to browse my complete set of Unity tutorials.

All the source code from this post is available on GitHub, so you can try it yourself. Let me know in the comments below if you have any questions, and I’ll be happy to answer them.

Leave a Reply

Your email address will not be published. Required fields are marked *