45 lines
1.4 KiB
C#
45 lines
1.4 KiB
C#
|
using UnityEngine;
|
||
|
using System.Collections;
|
||
|
|
||
|
public class EnemySpawner : MonoBehaviour
|
||
|
{
|
||
|
public GameObject enemyPrefab; // Reference to the enemy prefab
|
||
|
public float spawnInterval = 3f; // Time between each spawn (in seconds)
|
||
|
public float enemyLifetime = 5f; // Time before the enemy is destroyed (in seconds)
|
||
|
public Vector3 spawnPosition = new Vector3(0f, 0.6f, 0f); // Position to spawn enemies
|
||
|
|
||
|
void Start()
|
||
|
{
|
||
|
// Start the coroutine to spawn enemies at intervals
|
||
|
StartCoroutine(SpawnEnemies());
|
||
|
}
|
||
|
|
||
|
IEnumerator SpawnEnemies()
|
||
|
{
|
||
|
// Infinite loop to keep spawning enemies at intervals
|
||
|
while (true)
|
||
|
{
|
||
|
SpawnEnemy(); // Call method to spawn an enemy
|
||
|
yield return new WaitForSeconds(spawnInterval); // Wait for the spawn interval before spawning the next enemy
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void SpawnEnemy()
|
||
|
{
|
||
|
// Instantiate the enemy at the spawn position
|
||
|
GameObject newEnemy = Instantiate(enemyPrefab, spawnPosition, Quaternion.identity);
|
||
|
|
||
|
// Start a coroutine to destroy the enemy after a set time
|
||
|
StartCoroutine(DestroyEnemyAfterTime(newEnemy, enemyLifetime));
|
||
|
}
|
||
|
|
||
|
IEnumerator DestroyEnemyAfterTime(GameObject enemy, float time)
|
||
|
{
|
||
|
// Wait for the specified time
|
||
|
yield return new WaitForSeconds(time);
|
||
|
|
||
|
// Destroy the enemy after the time has passed
|
||
|
Destroy(enemy);
|
||
|
}
|
||
|
}
|