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. public class Spawner: MonoBehaviour {
  5. public GameObject[] enemies;
  6. public Vector3 spawnValues;
  7. public float spawnWait;
  8. public float spawnMostWait;
  9. public float spawnLeastWait;
  10. public int startWait;
  11. public bool stop;
  12. int randEnemy;
  13. void Start() {
  14. StartCoroutine(waitSpawner());
  15. }
  16. void Update() {
  17. spawnWait = Random.Range(spawnMostWait, spawnMostWait);
  18. }
  19. IEnumerator waitSpawner() {
  20. yield
  21. return new WaitForSeconds(startWait);
  22. while (!stop) {
  23. randEnemy = Random.Range(0, 2);
  24. Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), 1 f, Random.Range(-spawnValues.z, spawnValues.z));
  25. Instantiate(enemies[randEnemy], spawnPosition + transform.TransformPoint(0, 0, 0), gameObject.transform.rotation);
  26. yield
  27. return new WaitForSeconds(spawnWait);
  28. }
  29. }
  30. }
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.