randomly spawn enemies in unity in csharp

To randomly spawn enemies in Unity using C#, you can use the Instantiate() method coupled with Random.Range() to randomly set the position and rotation of each enemy spawned.

First, you need to create an empty GameObject as the parent of the enemies spawned, so you can keep your hierarchy clean. Then, create a prefab of your enemy game object.

main.cs
public GameObject enemyPrefab; // assign the enemy prefab in the inspector
public Transform enemyParent; // assign the parent object in the inspector
public float spawnDelay = 2f; // set the spawn delay in seconds
 
void Start()
{
    InvokeRepeating("SpawnEnemy", spawnDelay, spawnDelay);
}
 
void SpawnEnemy()
{
    Vector3 spawnPosition = new Vector3(Random.Range(-10f, 10f), 0f, Random.Range(-10f, 10f)); // set the spawn position randomly within the set range
    Quaternion spawnRotation = Quaternion.identity; // set the spawn rotation to no rotation
    GameObject enemy = Instantiate(enemyPrefab, spawnPosition, spawnRotation); // spawn the enemy game object
    enemy.transform.SetParent(enemyParent); // set the enemy's parent object
}
747 chars
17 lines

The above code randomly spawns an enemy every spawnDelay seconds, within the range of -10 to 10 on the x and z axes. The spawned enemy is also assigned to the enemyParent object for organization purposes.

Note that the InvokeRepeating() function is used to repeatedly call the SpawnEnemy() method at the set delay time. This is one way to spawn enemies in a consistent manner without overloading the system with spawn requests, as opposed to using a while loop or a Coroutine.

gistlibby LogSnag