Random spawning is a game development technique that involves creating game elements, such as objects or enemies, at unpredictable locations within a confined boundary or area. It is an essential tool used by game developers to introduce variety and unpredictability to the game world.
This Answer is part of the introductory series on how to build a first-person shooter game using Unity.
Let’s dive into what we’ll be creating together in this Answer.
Let’s see how we can randomly spawn GameObjects within a confined boundary.
Start by either creating a new Unity 3D project or opening an existing scene. Ensure it includes a “Main Camera” and a directional light. We’ll build upon the scene from the How to destroy an enemy GameObject on collision in Unity Answer.
To create enemies, use the cube primitive GameObject and attach a collider to it.
Note: If you are following the series, you can use the previously created one in the How to destroy an enemy GameObject on collision in Unity Answer.
To represent the spawn area in which we want to spawn enemies at random intervals, create a confined boundary using a combination of Vector3
values. Instead of using a collider, we can set up a range of minimum and maximum values for the X, Y, and Z coordinates. Randomly generate spawn positions within these ranges.
Let’s create the GameObjectSpawner
script, which will randomly create a specified number of objects within a confined boundary. The spawning is controlled by the range of possible object counts and random time delays between spawns, allowing for dynamic and varied gameplay experiences.
using System.Collections;using System.Collections.Generic;using UnityEngine;public class GameObjectSpawner : MonoBehaviour{public GameObject objectPrefab;public int minObjectsToSpawn = 5;public int maxObjectsToSpawn = 10;public float minSpawnDelay = 1f;public float maxSpawnDelay = 2f;public float fixedSpawnHeight = 2f; // Fixed Y-axis spawn positionpublic float minXPosition = -5f;public float maxXPosition = 5f;public float minZPosition = -5f;public float maxZPosition = 5f;void Start(){StartCoroutine(SpawnObjectsWithDelay());}IEnumerator SpawnObjectsWithDelay(){int numObjectsToSpawn = Random.Range(minObjectsToSpawn, maxObjectsToSpawn + 1);for (int i = 0; i < numObjectsToSpawn; i++){Vector3 spawnPosition = GetRandomSpawnPosition();Instantiate(objectPrefab, spawnPosition, Quaternion.identity);float randomDelay = Random.Range(minSpawnDelay, maxSpawnDelay);yield return new WaitForSeconds(randomDelay);}}Vector3 GetRandomSpawnPosition(){float randomX = Random.Range(minXPosition, maxXPosition);float randomZ = Random.Range(minZPosition, maxZPosition);return new Vector3(randomX, fixedSpawnHeight, randomZ);}}
Lines 24–36: The SpawnObjectsWithDelay
coroutine is responsible for spawning objects. It generates a random number between minObjectsToSpawn
and maxObjectsToSpawn
to determine how many objects to spawn.
Inside the for
loop, it calls the GetRandomSpawnPosition
method to get a random position within the specified boundary. It then instantiates objectPrefab
at spawnPosition
with no rotation (Quaternion.identity
).
After spawning each object, it introduces a random delay between minSpawnDelay
and maxSpawnDelay
using Random.Range
and yield return new WaitForSeconds
.
Lines 38–43: The GetRandomSpawnPosition
method generates a random position within the specified X and Z boundaries (minXPosition
, maxXPosition
, minZPosition
, maxZPosition
) while keeping the Y-axis position fixed at fixedSpawnHeight
.
Attach the script to an empty GameObject or a dedicated spawner GameObject in the scene. Set the parameters for the minimum and maximum number of GameObjects to spawn as well as the boundaries of the spawn area (e.g. minX, maxX, minY, maxY, minZ, maxZ).
Either attach the script to the plane GameObject if we only want enemies to spawn on the plane, or create another empty GameObject and add GameObjectSpawner
as a component to it. In this case, we will attach the script to the plane GameObject.
Test and fine-tune the script values to ensure that the GameObjects spawn randomly within the confined boundary. This will provide an engaging and dynamic environment for the game.
Note: Click the “Run” button below to start the game. Once the game is rendered, interact with it by clicking the “Output” screen. Alternatively, you can access the game by clicking the link provided after the “Your app can be found at:” text.
import React from 'react'; require('./style.css'); import ReactDOM from 'react-dom'; import App from './app.js'; ReactDOM.render( <App />, document.getElementById('root') );
Stay tuned for our next Answer, where we’ll cover the implementation of a reward-based system in Unity.
Next: How to implement a reward-based system in Unity.
Free Resources