Eggys Games

Unity - Spawning Objects Class in C#

Posted on by Eggy

Here is a nice simple class you can use if you want to spawn objects from another object in Unity. It allows you to simply drag and drop the class on an object and then in the inspector set the frequency of spawn, how fast to spawn and what to spawn.

It's quite simple yet very versatile to use in many projects. The timer keeps adding, when it goes over a certain amount you set known as the frequency then it will instantiate the object at its transform position and set the timer back to 0. Simple yet effective.

public class Spawn : MonoBehaviour {


    public Rigidbody2D ObjectToSpawn; 
    public Transform WhereToSpawn; 
    public int frequency; 
    public Vector3 random;

    private int spawntime = 0;

    void Update () {


        random = new Vector3 (Random.Range(0,5), 0, 0);

        spawntime++; 

        if (spawntime > frequency) {
            Instantiate (ObjectToSpawn, WhereToSpawn.position+random, WhereToSpawn.rotation);
            spawntime = 0; 
        }
        
    }

Putting our spawn code to good use by spawning zombies out a door