Runtime Create Enemies Using C# Scripts In Unity

Introduction

 
Unity has a powerful visual editor and is also capable of publishing to mobile. Unity makes things easier as compared to other platforms. In this article we will learn how one can spawn random Enemies at random times and positions using C# scripts.
 
Prerequisites
 
Unity Environment version 2018.4.19f1
 

Create a New Project

 
 

Create a plane in Unity

 
 
First, you have to open the Unity project. Create the Cube for your game.
 
 
Select the Cube on Click (Ctrl + D). Create a duplicate "Cube" in Unity.
 
 

Create the Folder

 
Right-click on Assets. Select Create >> Folder
 
 
Rename the Folder as Prefab and Materials.
 
 
Drag and drop the blue and red materials onto the cube in Unity.
 
 
Drag and drop the blue and red cube onto the Prefabs Folder in Unity.
 
 

Create The Empty GameObject

 
Click on the "GameObject" menu in the menu bar. Select Create Empty GameObject.
 
 
Rename the Empty GameObject as Spawner.
 
 

Create the Scripts

 
Right-click on Assets. Select Create >> C# script
 
 
Rename the Scripts as Spawner
 
 
Double click on the Spawner script. Write the code as shown below:
  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4.   
  5. public class Spawner: MonoBehaviour {  
  6.     public GameObject[] enemies;  
  7.     public Vector3 spawnValues;  
  8.     public float spawnWait;  
  9.     public float spawnMostWait;  
  10.     public float spawnLeastWait;  
  11.     public int startWait;  
  12.     public bool stop;  
  13.   
  14.     int randEnemy;  
  15.   
  16.     void Start() {  
  17.         StartCoroutine(waitSpawner());  
  18.     }  
  19.   
  20.     void Update() {  
  21.         spawnWait = Random.Range(spawnMostWait, spawnMostWait);  
  22.     }  
  23.   
  24.     IEnumerator waitSpawner() {  
  25.         yield  
  26.         return new WaitForSeconds(startWait);  
  27.   
  28.         while (!stop) {  
  29.             randEnemy = Random.Range(0, 2);  
  30.   
  31.             Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), 1 f, Random.Range(-spawnValues.z, spawnValues.z));  
  32.   
  33.             Instantiate(enemies[randEnemy], spawnPosition + transform.TransformPoint(0, 0, 0), gameObject.transform.rotation);  
  34.   
  35.             yield  
  36.             return new WaitForSeconds(spawnWait);  
  37.         }  
  38.     }  
  39. }  
Save the program and drag and drop the Spawner script onto the Spawner.
 
 
Drag and drop the prefab Blue and Red onto the Elements & fill the Spawner Details in unity
 
 
Click on the Play button as multiple enemies are created in Unity as you can see in the figure below.
 
 

Summary

 
In this article, we mainly focused on trying to generate enemy objects at particular positions and particular times in this article.