Search Unity

Free Spawn Script - Updated

Discussion in 'Scripting' started by CorruptedHeart, Jun 3, 2010.

  1. CorruptedHeart

    CorruptedHeart

    Joined:
    May 4, 2010
    Posts:
    379
    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.
    Code (csharp):
    1. // AUTHOR:Garth de Wet (Corrupted Heart)
    2. // CONTACT:mydeathofme[at]gmail[dot]com
    3. // FILENAME:Spawner.cs
    4. // PURPOSE:To allow spawning of different enemy types and different ways to spawn them.
    5. using UnityEngine;
    6. using System.Collections;
    7.  
    8. public class Spawner : MonoBehaviour
    9. {
    10.     //----------------------------------
    11.     // All the Enums
    12.     //----------------------------------
    13.     // Spawn types
    14.     public enum SpawnTypes
    15.     {
    16.         Normal,
    17.         Once,
    18.         Wave,
    19.         TimedWave
    20.     }
    21.     // The different Enemy levels
    22.     public enum EnemyLevels
    23.     {
    24.         Easy,
    25.         Medium,
    26.         Hard,
    27.         Boss
    28.     }
    29.     //---------------------------------
    30.     // End of the Enums
    31.     //---------------------------------
    32.    
    33.     // Enemy level to be spawnedEnemy
    34.     public EnemyLevels enemyLevel = EnemyLevels.Easy;
    35.    
    36.     //----------------------------------
    37.     // Enemy Prefabs
    38.     //----------------------------------
    39.     public GameObject EasyEnemy;
    40.     public GameObject MediumEnemy;
    41.     public GameObject HardEnemy;
    42.     public GameObject BossEnemy;
    43.     //----------------------------------
    44.     // End of Enemy Prefabs
    45.     //----------------------------------
    46.  
    47.     //----------------------------------
    48.     // Enemies and how many have been created and how many are to be created
    49.     //----------------------------------
    50.     public int totalEnemy = 10;
    51.     private int numEnemy = 0;
    52.     private int spawnedEnemy = 0;
    53.     //----------------------------------
    54.     // End of Enemy Settings
    55.     //----------------------------------
    56.  
    57.    
    58.     // The ID of the spawner
    59.     private int SpawnID;
    60.    
    61.     //----------------------------------
    62.     // Different Spawn states and ways of doing them
    63.     //----------------------------------
    64.     private bool waveSpawn = false;
    65.     public bool Spawn = true;
    66.     public SpawnTypes spawnType = SpawnTypes.Normal;
    67.     // timed wave controls
    68.     public float waveTimer = 30.0f;
    69.     private float timeTillWave = 0.0f;
    70.     //Wave controls
    71.     public int totalWaves = 5;
    72.     private int numWaves = 0;
    73.     //----------------------------------
    74.     // End of Different Spawn states and ways of doing them
    75.     //----------------------------------
    76.    
    77.     void Start()
    78.     {
    79.         // sets a random number for the id of the spawner
    80.         SpawnID = Random.Range(1, 500);
    81.     }
    82.    
    83.     // Draws a cube to show where the spawn point is... Useful if you don't have a object that show the spawn point
    84.     void OnDrawGizmos()
    85.     {
    86.         // Sets the color to red
    87.         Gizmos.color = Color.red;
    88.         //draws a small cube at the location of the gam object that the script is attached to
    89.         Gizmos.DrawCube(transform.position, new Vector3 (0.5f,0.5f,0.5f));
    90.     }
    91.    
    92.     void Update ()
    93.     {
    94.         if(Spawn)
    95.         {
    96.             // Spawns enemies everytime one dies
    97.             if (spawnType == SpawnTypes.Normal)
    98.             {
    99.                 // checks to see if the number of spawned enemies is less than the max num of enemies
    100.                 if(numEnemy < totalEnemy)
    101.                 {
    102.                     // spawns an enemy
    103.                     spawnEnemy();
    104.                 }
    105.             }
    106.             // Spawns enemies only once
    107.             else if (spawnType == SpawnTypes.Once)
    108.             {
    109.                 // checks to see if the overall spawned num of enemies is more or equal to the total to be spawned
    110.                 if(spawnedEnemy >= totalEnemy)
    111.                 {
    112.                     //sets the spawner to false
    113.                     Spawn = false;
    114.                 }
    115.                 else
    116.                 {
    117.                     // spawns an enemy
    118.                     spawnEnemy();
    119.                 }
    120.             }
    121.             //spawns enemies in waves, so once all are dead, spawns more
    122.             else if (spawnType == SpawnTypes.Wave)
    123.             {
    124.                 if(numWaves < totalWaves + 1)
    125.                 {
    126.                     if (waveSpawn)
    127.                     {
    128.                         //spawns an enemy
    129.                         spawnEnemy();
    130.                     }
    131.                     if (numEnemy == 0)
    132.                     {
    133.                         // enables the wave spawner
    134.                         waveSpawn = true;
    135.                         //increase the number of waves
    136.                         numWaves++;
    137.                     }
    138.                     if(numEnemy == totalEnemy)
    139.                     {
    140.                         // disables the wave spawner
    141.                         waveSpawn = false;
    142.                     }
    143.                 }
    144.             }
    145.             // Spawns enemies in waves but based on time.
    146.             else if(spawnType == SpawnTypes.TimedWave)
    147.             {
    148.                 // checks if the number of waves is bigger than the total waves
    149.                 if(numWaves <= totalWaves)
    150.                 {
    151.                     // Increases the timer to allow the timed waves to work
    152.                     timeTillWave += Time.deltaTime;
    153.                     if (waveSpawn)
    154.                     {
    155.                         //spawns an enemy
    156.                         spawnEnemy();
    157.                     }
    158.                     // checks if the time is equal to the time required for a new wave
    159.                     if (timeTillWave >= waveTimer)
    160.                     {
    161.                         // enables the wave spawner
    162.                         waveSpawn = true;
    163.                         // sets the time back to zero
    164.                         timeTillWave = 0.0f;
    165.                         // increases the number of waves
    166.                         numWaves++;
    167.                         // A hack to get it to spawn the same number of enemies regardless of how many have been killed
    168.                         numEnemy = 0;
    169.                     }
    170.                     if(numEnemy >= totalEnemy)
    171.                     {
    172.                         // diables the wave spawner
    173.                         waveSpawn = false;
    174.                     }
    175.                 }
    176.                 else
    177.                 {
    178.                     Spawn = false;
    179.                 }
    180.             }
    181.         }
    182.     }
    183.     // spawns an enemy based on the enemy level that you selected
    184.     private void spawnEnemy()
    185.     {
    186.         // To check which enemy prefab to instantiate
    187.         if (enemyLevel == EnemyLevels.Easy)
    188.         {
    189.             // Checks to see if there is a gameobject in the easy enemy var
    190.             if (EasyEnemy != null)
    191.             {
    192.                 // spawns the enemy
    193.                 GameObject Enemy = (GameObject) Instantiate(EasyEnemy, gameObject.transform.position, Quaternion.identity);
    194.                 // calls a function on the enemy that applies the spawner's ID to the enemy
    195.                 Enemy.SendMessage("setName", SpawnID);
    196.             }
    197.             else
    198.             {
    199.                 //Shows a debug message if there is no prefab
    200.                 Debug.Log("ERROR: No easy enemy Prefab loaded");
    201.             }
    202.         }
    203.         else if (enemyLevel == EnemyLevels.Medium)
    204.         {
    205.             // Checks to see if there is a gameobject in the medium enemy var
    206.             if (MediumEnemy != null)
    207.             {
    208.                 // spawns the enemy
    209.                 GameObject Enemy = (GameObject) Instantiate(MediumEnemy, gameObject.transform.position, Quaternion.identity);
    210.                 // calls a function on the enemy that applies the spawner's ID to the enemy
    211.                 Enemy.SendMessage("setName", SpawnID);
    212.             }
    213.             else
    214.             {
    215.                 //Shows a debug message if there is no prefab
    216.                 Debug.Log("ERROR: No medium enemy Prefab loaded");
    217.             }
    218.         }
    219.         else if (enemyLevel == EnemyLevels.Hard)
    220.         {
    221.             // Checks to see if there is a gameobject in the hard enemy var
    222.             if (HardEnemy != null)
    223.             {
    224.                 // spawns the enemy
    225.                 GameObject Enemy = (GameObject) Instantiate(HardEnemy, gameObject.transform.position, Quaternion.identity);
    226.                 // calls a function on the enemy that applies the spawner's ID to the enemy
    227.                 Enemy.SendMessage("setName", SpawnID);
    228.             }
    229.             else
    230.             {
    231.                 //Shows a debug message if there is no prefab
    232.                 Debug.Log("ERROR: No hard enemy Prefab loaded");
    233.             }
    234.         }
    235.         else if (enemyLevel == EnemyLevels.Boss)
    236.         {
    237.             // Checks to see if there is a gameobject in the boss enemy var
    238.             if (BossEnemy != null)
    239.             {
    240.                 // spawns the enemy
    241.                 GameObject Enemy = (GameObject) Instantiate(BossEnemy, gameObject.transform.position, Quaternion.identity);
    242.                 // calls a function on the enemy that applies the spawner's ID to the enemy
    243.                 Enemy.SendMessage("setName", SpawnID);
    244.             }
    245.             else
    246.             {
    247.                 //Shows a debug message if there is no prefab
    248.                 Debug.Log("ERROR: No boss enemy Prefab loaded");
    249.             }
    250.         }
    251.         // Increase the total number of enemies spawned and the number of spawned enemies
    252.         numEnemy++;
    253.         spawnedEnemy++;
    254.     }
    255.     // Call this function from the enemy when it "dies" to remove an enemy count
    256.     public void killEnemy(int sID)
    257.     {
    258.         // if the enemy's spawnId is equal to this spawnersID then remove an enemy count
    259.         if (SpawnID == sID)
    260.         {
    261.             numEnemy--;
    262.         }
    263.     }
    264.     //enable the spawner based on spawnerID
    265.     public void enableSpawner(int sID)
    266.     {
    267.         if (SpawnID == sID)
    268.         {
    269.             Spawn = true;
    270.         }
    271.     }
    272.     //disable the spawner based on spawnerID
    273.     public void disableSpawner(int sID)
    274.     {
    275.         if(SpawnID == sID)
    276.         {
    277.             Spawn = false;
    278.         }
    279.     }
    280.     // returns the Time Till the Next Wave, for a interface, ect.
    281.     public float TimeTillWave
    282.     {
    283.         get
    284.         {
    285.             return timeTillWave;
    286.         }
    287.     }
    288.     // Enable the spawner, useful for trigger events because you don't know the spawner's ID.
    289.     public void enableTrigger()
    290.     {
    291.         Spawn = true;
    292.     }
    293. }
    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.
     
  2. Route 66 Rambler

    Route 66 Rambler

    Joined:
    Mar 12, 2010
    Posts:
    45
    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.
     
  3. CorruptedHeart

    CorruptedHeart

    Joined:
    May 4, 2010
    Posts:
    379
    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.
     
  4. CorruptedHeart

    CorruptedHeart

    Joined:
    May 4, 2010
    Posts:
    379
  5. CorruptedHeart

    CorruptedHeart

    Joined:
    May 4, 2010
    Posts:
    379
    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.
     
  6. Kirkja

    Kirkja

    Joined:
    Oct 18, 2009
    Posts:
    7
    For me, I like the more dynamic approach of using an ArrayList. This would make the spawner more run time flexible for scripting.
     
  7. CorruptedHeart

    CorruptedHeart

    Joined:
    May 4, 2010
    Posts:
    379
  8. raymix

    raymix

    Joined:
    Aug 25, 2010
    Posts:
    192
    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
     
  9. CorruptedHeart

    CorruptedHeart

    Joined:
    May 4, 2010
    Posts:
    379
    Thank you, I will fix that up ASAP.

    Glad you like it
     
  10. RoDester

    RoDester

    Joined:
    May 21, 2011
    Posts:
    64
    I get a error on the second script the AI script :(

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

    CorruptedHeart

    Joined:
    May 4, 2010
    Posts:
    379
    What error are you getting?
     
  12. RoDester

    RoDester

    Joined:
    May 21, 2011
    Posts:
    64
    Assets/aispawn.cs(15,6): error CS0116: A namespace can only contain types and namespace declarations

    Same error at difrent lines.
     
  13. CorruptedHeart

    CorruptedHeart

    Joined:
    May 4, 2010
    Posts:
    379
    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.
     
  14. RoDester

    RoDester

    Joined:
    May 21, 2011
    Posts:
    64
    It worked thank you!
     
  15. CorruptedHeart

    CorruptedHeart

    Joined:
    May 4, 2010
    Posts:
    379
    No problem
     
  16. ghost012

    ghost012

    Joined:
    Jan 3, 2013
    Posts:
    13
    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
     
  17. Daryll

    Daryll

    Joined:
    Jan 24, 2013
    Posts:
    1
    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..
     
  18. CorruptedHeart

    CorruptedHeart

    Joined:
    May 4, 2010
    Posts:
    379
    @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.
     
  19. airesdav

    airesdav

    Joined:
    Nov 13, 2012
    Posts:
    128
    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
     
  20. airesdav

    airesdav

    Joined:
    Nov 13, 2012
    Posts:
    128
    is anyone out there, no pun intended :)
     
  21. CorruptedHeart

    CorruptedHeart

    Joined:
    May 4, 2010
    Posts:
    379
    Hi airesdav, sorry for the late reply.

    The Wiki version of the Spawner is quite outdated compared to the version on the Asset Store.

    Within the Asset Store Version there is a Readme.pdf that contains an updated short tutorial on getting the system to work.

    To help out with your current issue. The wiki version used BroadcastMessage to broadcast to all children GameObjects of the Spawner tagged GameObject.

    For the creating the Child Object part.
    1. Create an empty GameObject called Parent Spawner - (This is simply so you can visually see what it is.)
    2. Set that GameObject's tag to Spawner
    3. Set the position of that object to 0,0,0
    4. Create another empty GameObject called: SpawnPoint - (Names are simply to help out visually)
    5. Drag the newly created object onto the Parent Spawner to make it a Child Object
    6. Add the Spawner.cs component to the SpawnPoint Object.
    Then follow the rest of the guide.

    Regards,
    Garth
     
  22. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    You don't need to be running this code in update. Its bad form, especially if you are looking to squeeze every drop of performance out.

    You should replace the Update function with something like this which will run approximately 10x/second, which is more than sufficient for a spawner.

    Code (csharp):
    1.  
    2.  
    3. void Start()
    4. {
    5.   InvokeRepeating("SpawnUpdate", 0.1f, 0.1f);
    6. }
    7.  
    8. void SpawnUpdate()  // this will be your update replacement
    9. {
    10.  
    11. }
    12.  
    13.  
     
  23. omelchor

    omelchor

    Joined:
    Jun 15, 2011
    Posts:
    20
    Thanks!
     
  24. SniperEvan

    SniperEvan

    Joined:
    Mar 3, 2013
    Posts:
    161
    Looks great! Thanks for the code!

    If I use this in a game do you want to be in the credits? And real name or username?
     
  25. CorruptedHeart

    CorruptedHeart

    Joined:
    May 4, 2010
    Posts:
    379
    No problem, there is no credits necessary for Spawner but if you want to include me in the credits then by all means. You can simply credit Garth de Wet if you go ahead with crediting.
     
  26. CorruptedHeart

    CorruptedHeart

    Joined:
    May 4, 2010
    Posts:
    379
  27. SniperEvan

    SniperEvan

    Joined:
    Mar 3, 2013
    Posts:
    161
    Thanks, your awesome :)
     
  28. Rose-Remnant

    Rose-Remnant

    Joined:
    Nov 14, 2012
    Posts:
    123
    love the script but can you make a trigger zone with the player tag ?
     
  29. realme2pro23

    realme2pro23

    Joined:
    May 24, 2019
    Posts:
    1



    its giving me error of set name has no reciever
     
  30. Snake_46

    Snake_46

    Joined:
    Sep 13, 2019
    Posts:
    1
    There's a missing script attached to the spawned object. The spawner script(above) is looking for a function on the spawned object called 'setName'.

    Solution: Create a new c# script calling is something like -aispawn. Add a new function to the script called setName.
    ------------------------------------------------------------------------
    using System.Collections;
    using UnityEngine;

    public class aispawn : MonoBehaviour
    {

    void setName()
    {}
    }
    -------------------------------------------------------------------------------------
    Attach the tiny script to all the prefabs you want to spawn.
     
  31. yusuf1252006

    yusuf1252006

    Joined:
    Dec 17, 2020
    Posts:
    1
    hello when my e nemy spawns i cant see him but there is an clone of him.
    on the scene i can see him too but not in game
     
  32. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    This post is TEN YEARS OLD!! Can some moderator PLEASE lock it?

    Don't reply to ten-year-old posts... Instead, start your own... it's FREE!

    When you post, here is how to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    If you post code, please use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/
     
    metaldc4life likes this.