Skip to content

Instantly share code, notes, and snippets.

@silver-hornet
Last active July 18, 2022 00:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save silver-hornet/bc5d651295d92cb251c6f97ca03fc9eb to your computer and use it in GitHub Desktop.
Save silver-hornet/bc5d651295d92cb251c6f97ca03fc9eb to your computer and use it in GitHub Desktop.
Object Spawner
// This script will spawn an instance of a prefab from a random spawn position.
// Create an ObjectSpawner game object and add this script to it.
// Create one or more child game objects and set each transform to the position you'd like to spawn objects from.
using UnityEngine;
public class ObjectSpawner : MonoBehaviour
{
[SerializeField] float spawnDelay = 0.3f;
[SerializeField] GameObject objectPrefab;
[SerializeField] Transform[] spawnPoints;
float nextTimeToSpawn = 0f;
void Update()
{
if (nextTimeToSpawn <= Time.time)
{
SpawnObject();
nextTimeToSpawn = Time.time + spawnDelay;
}
}
void SpawnObject()
{
int randomIndex = Random.Range(0, spawnPoints.Length);
Transform spawnPoint = spawnPoints[randomIndex];
Instantiate(objectPrefab, spawnPoint.position, spawnPoint.rotation);
}
}
// Version that automatically gets spawn points from the ObjectSpawner's child objects, while not including itself
//public class Spawner : MonoBehaviour
//{
// float spawnDelay = 1f;
// [SerializeField] GameObject objectPrefab;
// [SerializeField] List<Transform> spawnPoints;
// float nextTimeToSpawn = 0f;
// void Start()
// {
// spawnPoints.AddRange(GetComponentsInChildren<Transform>());
// spawnPoints.Remove(transform);
// }
// void Update()
// {
// if (nextTimeToSpawn <= Time.time)
// {
// SpawnObject();
// nextTimeToSpawn = Time.time + spawnDelay;
// }
// }
// void SpawnObject()
// {
// int randomIndex = Random.Range(0, spawnPoints.Count);
// Transform spawnPoint = spawnPoints[randomIndex];
// Instantiate(objectPrefab, spawnPoint.position, spawnPoint.rotation);
// }
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment