Free Spawn Script - Updated

This is a spawn script that I have been working on for a while but I figured that this will be good enough for release to the public to use as they see fit.

It’s used for spawning enemy and is fully commented.

// AUTHOR:Garth de Wet (Corrupted Heart)
// CONTACT:mydeathofme[at]gmail[dot]com
// FILENAME:Spawner.cs
// PURPOSE:To allow spawning of different enemy types and different ways to spawn them.
using UnityEngine;
using System.Collections;

public class Spawner : MonoBehaviour
{
	//----------------------------------
	// All the Enums
	//----------------------------------
	// Spawn types
	public enum SpawnTypes
    {
		Normal,
		Once,
		Wave,
		TimedWave
    }
	// The different Enemy levels
	public enum EnemyLevels
    {
		Easy,
		Medium,
		Hard,
		Boss
    }
	//---------------------------------
	// End of the Enums
	//---------------------------------
	
	// Enemy level to be spawnedEnemy
	public EnemyLevels enemyLevel = EnemyLevels.Easy;
	
	//----------------------------------
	// Enemy Prefabs
	//----------------------------------
	public GameObject EasyEnemy;
	public GameObject MediumEnemy;
	public GameObject HardEnemy;
	public GameObject BossEnemy;
	//----------------------------------
	// End of Enemy Prefabs
	//----------------------------------

	//----------------------------------
	// Enemies and how many have been created and how many are to be created
	//----------------------------------
	public int totalEnemy = 10;
	private int numEnemy = 0;
	private int spawnedEnemy = 0;
	//----------------------------------
	// End of Enemy Settings
	//----------------------------------

	
	// The ID of the spawner
	private int SpawnID;
	
	//----------------------------------
	// Different Spawn states and ways of doing them
	//----------------------------------
	private bool waveSpawn = false;
	public bool Spawn = true;
	public SpawnTypes spawnType = SpawnTypes.Normal;
	// timed wave controls
	public float waveTimer = 30.0f;
	private float timeTillWave = 0.0f;
	//Wave controls
	public int totalWaves = 5;
	private int numWaves = 0;
	//----------------------------------
	// End of Different Spawn states and ways of doing them
	//----------------------------------
	
	void Start()
	{
		// sets a random number for the id of the spawner
		SpawnID = Random.Range(1, 500);
	}
	
	// Draws a cube to show where the spawn point is... Useful if you don't have a object that show the spawn point
	void OnDrawGizmos()
	{
		// Sets the color to red
		Gizmos.color = Color.red;
		//draws a small cube at the location of the gam object that the script is attached to
		Gizmos.DrawCube(transform.position, new Vector3 (0.5f,0.5f,0.5f));
	}
	
	void Update ()
	{
		if(Spawn)
		{
			// Spawns enemies everytime one dies
			if (spawnType == SpawnTypes.Normal)
			{
				// checks to see if the number of spawned enemies is less than the max num of enemies
				if(numEnemy < totalEnemy)
				{
					// spawns an enemy
					spawnEnemy();
				}
			}
			// Spawns enemies only once
			else if (spawnType == SpawnTypes.Once)
			{
				// checks to see if the overall spawned num of enemies is more or equal to the total to be spawned
				if(spawnedEnemy >= totalEnemy)
				{
					//sets the spawner to false
					Spawn = false;
				}
				else
				{
					// spawns an enemy
					spawnEnemy();
				}
			}
			//spawns enemies in waves, so once all are dead, spawns more
			else if (spawnType == SpawnTypes.Wave)
			{
				if(numWaves < totalWaves + 1)
				{
					if (waveSpawn)
					{
						//spawns an enemy
						spawnEnemy();
					}
					if (numEnemy == 0)
					{
						// enables the wave spawner
						waveSpawn = true;
						//increase the number of waves
						numWaves++;
					}
					if(numEnemy == totalEnemy)
					{
						// disables the wave spawner
						waveSpawn = false;
					}
				}
			}
			// Spawns enemies in waves but based on time.
			else if(spawnType == SpawnTypes.TimedWave)
			{
				// checks if the number of waves is bigger than the total waves
				if(numWaves <= totalWaves)
				{
					// Increases the timer to allow the timed waves to work
					timeTillWave += Time.deltaTime;
					if (waveSpawn)
					{
						//spawns an enemy
						spawnEnemy();
					}
					// checks if the time is equal to the time required for a new wave
					if (timeTillWave >= waveTimer)
					{
						// enables the wave spawner
						waveSpawn = true;
						// sets the time back to zero
						timeTillWave = 0.0f;
						// increases the number of waves
						numWaves++;
						// A hack to get it to spawn the same number of enemies regardless of how many have been killed
						numEnemy = 0;
					}
					if(numEnemy >= totalEnemy)
					{
						// diables the wave spawner
						waveSpawn = false;
					}
				}
				else
				{
					Spawn = false;
				}
			}
		}
	}
	// spawns an enemy based on the enemy level that you selected
	private void spawnEnemy()
	{
		// To check which enemy prefab to instantiate
		if (enemyLevel == EnemyLevels.Easy)
		{
			// Checks to see if there is a gameobject in the easy enemy var
			if (EasyEnemy != null)
			{
				// spawns the enemy
				GameObject Enemy = (GameObject) Instantiate(EasyEnemy, gameObject.transform.position, Quaternion.identity);
				// calls a function on the enemy that applies the spawner's ID to the enemy
				Enemy.SendMessage("setName", SpawnID);
			}
			else
			{
				//Shows a debug message if there is no prefab
				Debug.Log("ERROR: No easy enemy Prefab loaded");
			}
		}
		else if (enemyLevel == EnemyLevels.Medium)
		{
			// Checks to see if there is a gameobject in the medium enemy var
			if (MediumEnemy != null)
			{
				// spawns the enemy
				GameObject Enemy = (GameObject) Instantiate(MediumEnemy, gameObject.transform.position, Quaternion.identity);
				// calls a function on the enemy that applies the spawner's ID to the enemy
				Enemy.SendMessage("setName", SpawnID);
			}
			else
			{
				//Shows a debug message if there is no prefab
				Debug.Log("ERROR: No medium enemy Prefab loaded");
			}
		}
		else if (enemyLevel == EnemyLevels.Hard)
		{
			// Checks to see if there is a gameobject in the hard enemy var
			if (HardEnemy != null)
			{
				// spawns the enemy
				GameObject Enemy = (GameObject) Instantiate(HardEnemy, gameObject.transform.position, Quaternion.identity);
				// calls a function on the enemy that applies the spawner's ID to the enemy
				Enemy.SendMessage("setName", SpawnID);
			}
			else
			{
				//Shows a debug message if there is no prefab
				Debug.Log("ERROR: No hard enemy Prefab loaded");
			}
		}
		else if (enemyLevel == EnemyLevels.Boss)
		{
			// Checks to see if there is a gameobject in the boss enemy var
			if (BossEnemy != null)
			{
				// spawns the enemy
				GameObject Enemy = (GameObject) Instantiate(BossEnemy, gameObject.transform.position, Quaternion.identity);
				// calls a function on the enemy that applies the spawner's ID to the enemy
				Enemy.SendMessage("setName", SpawnID);
			}
			else
			{
				//Shows a debug message if there is no prefab
				Debug.Log("ERROR: No boss enemy Prefab loaded");
			}
		}
		// Increase the total number of enemies spawned and the number of spawned enemies
		numEnemy++;
		spawnedEnemy++;
	}
	// Call this function from the enemy when it "dies" to remove an enemy count
	public void killEnemy(int sID)
	{
		// if the enemy's spawnId is equal to this spawnersID then remove an enemy count
		if (SpawnID == sID)
		{
			numEnemy--;
		}
	}
	//enable the spawner based on spawnerID
	public void enableSpawner(int sID)
	{
		if (SpawnID == sID)
		{
			Spawn = true;
		}
	}
	//disable the spawner based on spawnerID
	public void disableSpawner(int sID)
	{
		if(SpawnID == sID)
		{
			Spawn = false;
		}
	}
	// returns the Time Till the Next Wave, for a interface, ect.
	public float TimeTillWave
	{
		get
		{
			return timeTillWave;
		}
	}
	// Enable the spawner, useful for trigger events because you don't know the spawner's ID.
	public void enableTrigger()
	{
		Spawn = true;
	}
}

For the latest version and tips on how to use it you can go to http://www.corruptedheart.co.cc/p/spawner-script.html

EDIT: Updated code to the latest and added URL
EDIT 2010/06/06: Updated code to the latest.
EDIT 2010/06/07: Updated code to the latest.

5 Likes

Thanks, CH! There is a spot waiting for this script in my game right now. I’ll let you know if I find any issues once I’ve got it integrated into the project.

One thing that I did change after I posted was to check that a prefab was placed within the slot otherwise it won’t spawn that type even if you have it selected to spawn.

EDIT: Updated code in the OP.

Fixed a few bugs that I found so here’s the newly updated code

http://www.corruptedheart.co.cc/p/spawner-script.html

EDIT: Added a link to my blog where I am now posting updates to the script.
EDIT AGAIN: Updated script in first post with this one

I am curious as to whether or not I should make it an array of gameObjects instead of limiting it to 4 types of objects. Then through code one could simply change the spawning object to another type of object.

Feedback would be helpful.

For me, I like the more dynamic approach of using an ArrayList. This would make the spawner more run time flexible for scripting.

In case anyone is wondering and sorry to resurrect an old thread but the updated Spawner Script is available on the wiki:
http://www.unifycommunity.com/wiki/index.php?title=Enemy_Spawner

Hi, thanks for your Script mate. Tried it out its lovely…

Also please fix AI part on your wiki, it gives context error CS0103, because of lower case typo
from:
private int SpawnerId;
to
private int SpawnerID;

Thanks again for sharing it, i find it very useful

Thank you, I will fix that up ASAP.

Glad you like it

I get a error on the second script the AI script :frowning:

Assets/aispawn.cs(15,6): error CS0116: A namespace can only contain types and namespace declarations

What error are you getting?

Assets/aispawn.cs(15,6): error CS0116: A namespace can only contain types and namespace declarations

Same error at difrent lines.

Did you just copy the AI stuff directly into an empty file? If so, I just updated the Wiki with what should be in the file to be complete.

It worked thank you!

No problem

really good script,the only problem i have with it,it squerts out all the mobs from that one spawn point,all my mobs have rigged bodys and are flying all over the place,it does look funny though

Hello,

i’m new to Unity3D and i’m currently working on a RPG game for my thesis. i came across this Asset which i believe would be a great help. so downloaded it and imported the Asset but i get the error “The imported type `Spawner’ is defined multiple times”. i’m not sure if this is right place where i should post this but i would really appreciate it if someone could help me… thanks in advance…

@ghostly012 You will likely need to add some form on delay between spawning or apply an offset to the spawned objects.

@Daryll It is likely that you have a class called Spawner already defined somewhere, you might want to check for that.

Hi CorruptedHeart,

I have your spawner script from the wiki but i am having a bit of trouble with this below are the instructions, sorry of this sounds stupid:

I have created an empty gameobject and called it Spawner and tagged it,i ts said to create a child GameObject to spawner one i am confused, could you break down what that means doi create an emptygame object and call spawner one and how do i create a child object if so how is it relatie to Spawner one sorry for the confusion:

1.Create a tag: Spawner
2.Create an empty GameObject
3.Apply the tag Spawner to it
4.Create a child GameObject to the spawner one
5.Add Spawner.cs to the new child Object - (These will be your actual spawn points)
6.Append the AI part below to your AI script
7.Add enemy prefabs to the spaces provided or just add one
8.Select the Enemy level you want, provided there is a prefab for it
9.Set the style of spawn and time, ect.

Kind regards

is anyone out there, no pun intended :slight_smile: