You are currently viewing Object Spawning and De-spawning Made Easy in Unity

Object Spawning and De-spawning Made Easy in Unity

If you are developing a game in Unity, you may need to spawn various objects, such as players, enemies, bullets or any other items, at specific points or randomly throughout the game. In this tutorial, we will learn how to spawn objects in Unity, either randomly or at specific spawning points, and how to de-spawn them when they are no longer needed.

Creating Prefabs

Spawning Objects with Prefabs The first step to spawning objects in Unity is to use prefabs. Prefabs are like blueprints of an object, and they are realized when they are instanced in the scene. To create prefabs, you need to create a folder in the project directory and name it anything you want. For example, we can call it “Prefabs”. Then, reset the X, Y, Z coordinates of the objects you want to spawn, and drag them one by one into the folder you just created. Finally, delete the original “GameObjects” to keep things organized.

Spawning Objects at Specific Points

To spawn objects at specific points, you need to create empty objects over the level that will serve as spawning points. Then, create a script and name it “Spawner”. Add public properties to the script, such as “GameObject spawnItem” to assign the specific prefab to be spawned, “float frequency” to set how often new items should be spawned, and “float initialSpeed” to set the starting speed of the spawned object. Add a private property called “float lastSpawnedTime” to store the last time an object was spawned. Remove the start method, as it is not needed for this example.

In the update method of the script, evaluate whether it is time to spawn the next object, and spawn the object using the “Spawn” method. Instantiate the “spawnItem” prefab as a “newSpawnedObject”, set its position the same as the spawner with “transform.position”, use “Quaternion.identity” to face it in the default direction set by the prefab, and set the newSpawnedObject’s Rigidbody’s velocity vector towards the spawner forward position multiplied by initialSpeed to shoot out the ball. Finally, set the newSpawnedObject parent to be the spawner to keep the spawned objects organized by their spawner. Add the Spawner script for all the spawner “GameObjects”. Assign a different ball for each spawner, and set up different frequency and “initialSpeed” values, and rotate them towards different directions.

public class Spawner : MonoBehaviour
{
    public GameObject spawnItem;
    public float frequency = 1f;
    public float initialSpeed = 10f;

    private float lastSpawnedTime;

    private void Update()
    {
        if (Time.time > lastSpawnedTime + 1f / frequency)
        {
            Spawn();
            lastSpawnedTime = Time.time;
        }
    }

    public void Spawn()
    {
        GameObject newSpawnedObject = Instantiate(spawnItem, transform.position, Quaternion.identity);
        newSpawnedObject.GetComponent<Rigidbody>().velocity = transform.forward * initialSpeed;
        newSpawnedObject.transform.parent = transform;
    }
}

Spawning Objects Randomly

To spawn objects randomly, you can use the same Spawner script, but with a few modifications. Instead of spawning objects at specific points, set the spawning points randomly using the “Random.Range” function in the “Spawn” method. The X, Y, and Z coordinates of the spawning points can be determined using “Random.Range” within a specific range. For example, you can set the range for the X-axis between -10 and 10, the Y-axis between 0 and 5, and the Z-axis between -10 and 10.

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

public class RandomSpawner : MonoBehaviour
{
    public GameObject spawnItem;
    public float frequency;
    public float initialSpeed;
    public float minX, maxX, minY, maxY, minZ, maxZ;

    private float lastSpawnedTime;

    void Update()
    {
        if (Time.time > lastSpawnedTime + frequency)
        {
            Spawn();
            lastSpawnedTime = Time.time;
        }
    }

    public void Spawn()
    {
        Vector3 spawnPosition = new Vector3(Random.Range(minX, maxX), Random.Range(minY, maxY), Random.Range(minZ, maxZ));
        GameObject newSpawnedObject = Instantiate(spawnItem, spawnPosition, Quaternion.identity);
        Rigidbody rb = newSpawnedObject.GetComponent<Rigidbody>();
        rb.velocity = transform.forward * initialSpeed;
    }
}

De-spawning Objects

The final step is to de-spawn objects that are no longer needed. To do this, add a new script to the level boundary and call it “DeSpawner”. Add a private function called “OnTriggerEnter” with a collider parameter. This method will be called by the physics engine in case of any collision. In the method, add a Destroy “other.gameObject” command to remove the object that collided with the level boundary. Alternatively, you could add a timer on the spawned objects and destroy them when they expired.

public class DeSpawner : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        // Destroy the other object that collided with the boundary
        Destroy(other.gameObject);
    }
}

Conclusion In this tutorial, we learned how to spawn objects in Unity, either randomly or at specific points.

Subscribe for Kory Code Newsletter

* indicates required

Please select all the ways you would like to hear from 8 Continents Ltd.:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp’s privacy practices here.