void FixedUpdate() { // check if can spawn if (timeSinceSpawn >= spawnrate && spawn && enemyCount < maxEnemies) { // spawn a random enemy at random position determined by random radius + random angle float spawnRadius = Random.Range(minSpawnRadius, maxSpawnRadius); float spawnAngle = Random.Range(0f, 360f) * Mathf.Deg2Rad; // convert to coordinates Vector2 offset; offset.x = Mathf.Cos(spawnAngle) * spawnRadius; offset.y = Mathf.Sin(spawnAngle) * spawnRadius; // spawn the enemy and reset counter GameObject clone = Instantiate(enemyPrefab, playerRB.position + offset, Quaternion.identity); timeSinceSpawn = 0f; // Detect when an ennemy gets destroyed DestroyEventEmitter destroyEventEmitter = clone.AddComponent <DestroyEventEmitter>(); destroyEventEmitter.OnObjectDestroyedEvent += OnGameObjectDestroyed; enemyCount++; } else if (timeSinceSpawn < spawnrate) { timeSinceSpawn += 1f; } }
private void OnGameObjectDestroyed(DestroyEventEmitter emitter) { remainingEnemies--; emitter.OnObjectDestroyedEvent -= OnGameObjectDestroyed; if (remainingEnemies <= 0) { remainingEnemies = 3; SpawnObjects(); } }
private IEnumerator SpawnObjects() { WaitForSeconds wait = new WaitForSeconds(spawnDelay); // Initial wait for the first spawn yield return(new WaitForSeconds(spawnTime)); for (int x = spawnCount; x > 0; --x) { // this uses a random number generator to pick from the list of six options int y = UnityEngine.Random.Range(1, 6); if (y == 1) { GameObject newBody = Instantiate(prefabA, transform.position, transform.rotation); } if (y == 2) { GameObject newBody = Instantiate(prefabB, transform.position, transform.rotation); } if (y == 3) { GameObject newBody = Instantiate(prefabC, transform.position, transform.rotation); } if (y == 4) { GameObject newBody = Instantiate(prefabD, transform.position, transform.rotation); } if (y == 5) { GameObject newBody = Instantiate(prefabE, transform.position, transform.rotation); } if (y == 6) { GameObject newBody = Instantiate(prefabF, transform.position, transform.rotation); } if (y <= 0 | y > 6) { GameObject newBody = Instantiate(prefabA, transform.position, transform.rotation); } // Detect when an enemy gets destroyed, emitter mechanics, I will admit I am new to realtime applications // this adds an emitter to the items spawned to allow a listen event for destruction DestroyEventEmitter destroyEventEmitter = newBody.AddComponent <DestroyEventEmitter>(); destroyEventEmitter.OnObjectDestroyedEvent += OnGameObjectDestroyed; remainingEnemies++; // Wait before next spawn prior to spawning again yield return(wait); } }
private void OnGameObjectDestroyed(DestroyEventEmitter emitter) { enemyCount--; emitter.OnObjectDestroyedEvent -= OnGameObjectDestroyed; }