Unity Random Prefab Spawner Script



This script that I want to share with you is a simple script to generate randomly spawned prefab objects across your Unity scene.

To use it, first make some multiple empty game objects as spawn points on your scene at different positions. Then apply a specific tag to them.

Then make an empty game object as the holder of this script, name it anything. Then attach the script to it. Type the tag that you were using, then type how many prefabs are you using. Next is to drag and drop your prefabs to the prefab list in the inspector. That’s all, run your game and you will see your prefabs are spawned on those spawn points.

There is an option to always span or not. If you choose to not always to span, it will randomly spawn the prefab or not on each spawn point.

So here is the script, I call it TNRandomSpawner:

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

public class TNRandomSpawner : MonoBehaviour
{
	
	public string spawnPointTag = "sometag";
	public bool alwaysSpawn = true;
	
	public List<GameObject> prefabsToSpawn;
	
    // Start is called before the first frame update
    void Start()
    {
        GameObject[] spawnPoints = GameObject.FindGameObjectsWithTag(spawnPointTag);
		foreach(GameObject spawnPoint in spawnPoints){
			int randomPrefab = Random.Range(0, prefabsToSpawn.Count);
			if(alwaysSpawn){
				GameObject pts = Instantiate(prefabsToSpawn[randomPrefab]);
				pts.transform.position = spawnPoint.transform.position;
			}else{
				int spawnOrNot = Random.Range(0, 2);
				if(spawnOrNot == 0){
					GameObject pts = Instantiate(prefabsToSpawn[randomPrefab]);
					pts.transform.position = spawnPoint.transform.position;
				}
			}
		}
    }

}
loading...

Leave a Reply

Your email address will not be published.