Skip to content

ThirteeNov

My personal blog about coding and internet

Menu
  • About me
  • About Zofia Kreasi
  • Cart
  • Checkout
  • Making an airplane game from scratch in Unity
  • My account
  • Privacy Policy
  • Privacy Policy – zkLeaderboard
  • Sample Page
  • Shop
  • Tutorials on Learning JavaScript
  • ZKAccounts – Privacy Policy
Menu

Unity Random Prefab Spawner Script

Posted on March 15, 2021March 15, 2021 by Habibie

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;
				}
			}
		}
    }

}
Post Views: 434
ciihuy2020

Welcome!

  • My YouTube Channel
  • My GitHub Page
  • About me

Categories

  • 3DVista
  • Android
  • Apache
  • C#
  • Cordova
  • Electron & Node JS
  • HTML5, CSS & JavaScript
  • iOS
  • Let's Make Unity Games
  • Misc
  • Photoshop
  • PHP
  • Python
  • Uncategorized
  • Unity
  • WordPress

Recent Posts

  • Make objects like wires and cables easily in Unity using Ciihuy Curved Mesh
  • [SOLVED] Can’t Add Custom Domain to Blogger After Losing CNAME Verification
  • iOS App Icon Generator by CiihuyCom
  • Advanced Blinking Marker Script to show objects position in your game canvas
  • Ciihuy Images Merger – Fast & Easy Online Image Combiner
© 2025 ThirteeNov | Powered by Superbs Personal Blog theme