Spawning ObstaclesHow To Spawn Objects in Unity

Author Waldo
Published September 25, 2018

In this tutorial I explain how to write a C# script that will allow you to spawn obstacles onto your scene using prefabs and instantiate.

Video Walkthrough

  • 1:00 Adding a CircleCollider2D, Rigidbody2D
  • 1:37 Adding a script to move the game objects
  • 3:40 Removing objects from the scene once they leave the screen
  • 5:00 Creating a prefab
  • 5:40 Adding a script to spawn the objects
  • 6:30 Using instantiate
  • 8:25 Using Coroutines and IENumerator 

Source Code for asteroid.cs

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

public class asteroid : MonoBehaviour {
    public float speed = 10.0f;
    private Rigidbody2D rb;
    private Vector2 screenBounds;


    // Use this for initialization
    void Start () {
        rb = this.GetComponent<Rigidbody2D>();
        rb.velocity = new Vector2(-speed, 0);
        screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));

    }

    // Update is called once per frame
    void Update () {
        if(transform.position.x < screenBounds.x * 2){
            Destroy(this.gameObject);
        }
    }
}

Source Code for deployAsteroid.cs

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

public class deployAsteroids : MonoBehaviour {
    public GameObject asteroidPrefab;
    public float respawnTime = 1.0f;
    private Vector2 screenBounds;

    // Use this for initialization
    void Start () {
        screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
        StartCoroutine(asteroidWave());
    }
    private void spawnEnemy(){
        GameObject a = Instantiate(asteroidPrefab) as GameObject;
        a.transform.position = new Vector2(screenBounds.x * -2, Random.Range(-screenBounds.y, screenBounds.y));
    }
    IEnumerator asteroidWave(){
        while(true){
            yield return new WaitForSeconds(respawnTime);
            spawnEnemy();
        }
    }
}

This tutorial is sponsored by this community

In order to stick to our mission of keeping education free, our videos and the content of this website rely on the support of this community. If you have found value in anything we provide, and if you are able to, please consider contributing to our Patreon. If you can’t afford to financially support us, please be sure to like, comment and share our content — it is equally as important.

Join The Community

Discussion

Browse Tutorials About