This tutorial on Unity Random Enemy Instantiation will demonstrate how to combine the Unity Randomize function with instantiation to create two different enemies at two different locations; if one enemy is destroyed, another enemy will appear; at all times there will be one enemy facing the player. An overview of this tutorial can be found in the following video link, though you will need the code and some explanations below as well:
To set this up, you will need a platform or terrain to work on, a First Person Controller, two Empty Game Objects named egoSpawnLoc1 and egoSpawnLoc2, a third Empty Game Object named CodeHolder, and two enemies named redOgre and greenBeast. The enemies can be simple sphere or capsule game objects for now, but they should look different so you can tell if your code is working or not. Note the setup in the screenshot at right. You will also need the ability to shoot a projectile in order to destroy an enemy. I covered the ability to shoot a projectile in Unity Shoot Wall. Note that the image can be enlarged by clicking on it. unity enemy spawn basic 1. Move egoSpawnLoc1 and egoSpawnLoc2 to different areas on your platform or terrain. Make sure to give all your Empty Game Objects a colored icon so you can see and find them easily. Notice in the screenshot that my egoSpawnLoc1 is red, which will be the same color as my redOgre, just to keep things organized while we are testing functionality. 2. The codeHolder Empty Game Object is just there to hold the code; we really don’t want to put any code on an enemy that is going to be destroyed, so it’s better to put our code on a game object that is outside of the conflict. 3. You must have the ability to destroy the enemies, and in this case we are doing it by shooting projectiles. 4. None of the enemies or projectiles will be in the scene – they are instantiated, or created, as needed. Bullets are created when you click the left mouse button, and enemies are created every time you destroy an enemy. 5. Create and attach EnemySpawnBasic.js to the CodeHolder. Notice a few things about SpawnEnemyBasic.js; for one, it has a static variable called enemyCount. If enemyCount is less than 1, another enemy is created. Then, based on our Random number, we spawn another entity and increment the enemyCount variable to enemyCount + 1, so the function cannot run again until an enemy is destroyed. Which leads us to our next code example. Now create another Javascript program called EnemyHit.js. Attach this script to both of your enemy game objects (attach it to both redOgre and greenBeast). Notice that in this code we are changing the value of a static variable in the script EnemySpawnBasic.js. Static variables are a powerful method of inter-script communications. If the enemy detects a bullet, it will set enemyCount to one less, causing EnemySpawnBasic.js to spawn yet another enemy!