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:
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
-
- public class Spawner: MonoBehaviour {
- public GameObject[] enemies;
- public Vector3 spawnValues;
- public float spawnWait;
- public float spawnMostWait;
- public float spawnLeastWait;
- public int startWait;
- public bool stop;
-
- int randEnemy;
-
- void Start() {
- StartCoroutine(waitSpawner());
- }
-
- void Update() {
- spawnWait = Random.Range(spawnMostWait, spawnMostWait);
- }
-
- IEnumerator waitSpawner() {
- yield
- return new WaitForSeconds(startWait);
-
- while (!stop) {
- randEnemy = Random.Range(0, 2);
-
- Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), 1 f, Random.Range(-spawnValues.z, spawnValues.z));
-
- Instantiate(enemies[randEnemy], spawnPosition + transform.TransformPoint(0, 0, 0), gameObject.transform.rotation);
-
- yield
- return new WaitForSeconds(spawnWait);
- }
- }
- }
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.