Spawning ObstaclesHow To Spawn Objects in Unity

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.

In this video you will learn:

  • 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();
        }
    }
}

LINK TO THIS POST

SHARE THIS POST


DISCUSSION