85 lines
2.9 KiB
C#
85 lines
2.9 KiB
C#
|
using System.Collections;
|
||
|
using System.Collections.Generic;
|
||
|
using UnityEngine;
|
||
|
|
||
|
namespace BulletHellTemplate
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// Spawns boxes at defined intervals within a specified area, avoiding obstacles with certain tags.
|
||
|
/// </summary>
|
||
|
public class BoxSpawner : MonoBehaviour
|
||
|
{
|
||
|
[Header("Spawner Settings")]
|
||
|
public int maxBoxes = 5; // Maximum number of boxes to maintain in the scene
|
||
|
public float spawnCooldown = 5f; // Cooldown in seconds between spawns
|
||
|
public GameObject boxPrefab; // Prefab of the BoxEntity to spawn
|
||
|
public float spawnRadius = 10f; // Radius within which boxes can be spawned
|
||
|
|
||
|
private List<GameObject> currentBoxes = new List<GameObject>(); // List to keep track of spawned boxes
|
||
|
private float cooldownTimer; // Timer to track cooldown between spawns
|
||
|
|
||
|
void Start()
|
||
|
{
|
||
|
cooldownTimer = spawnCooldown;
|
||
|
}
|
||
|
|
||
|
void Update()
|
||
|
{
|
||
|
// Do not update the spawner if the game is paused
|
||
|
if (GameplayManager.Singleton.IsPaused())
|
||
|
return;
|
||
|
|
||
|
cooldownTimer -= Time.deltaTime;
|
||
|
|
||
|
// Check if it's time to spawn a new box and if the max number hasn't been reached
|
||
|
if (cooldownTimer <= 0 && currentBoxes.Count < maxBoxes)
|
||
|
{
|
||
|
SpawnBox();
|
||
|
cooldownTimer = spawnCooldown; // Reset cooldown timer
|
||
|
}
|
||
|
|
||
|
// Clean up null entries if boxes have been destroyed
|
||
|
currentBoxes.RemoveAll(box => box == null);
|
||
|
}
|
||
|
|
||
|
/// <summary>
|
||
|
/// Spawns a box at a random position within the spawn radius, avoiding walls.
|
||
|
/// </summary>
|
||
|
private void SpawnBox()
|
||
|
{
|
||
|
Vector3 spawnPoint = Vector3.zero;
|
||
|
bool validPlacement = false;
|
||
|
|
||
|
// Attempt to find a valid spawn location
|
||
|
for (int attempts = 0; attempts < 10; attempts++) // Limit attempts to avoid infinite loops
|
||
|
{
|
||
|
spawnPoint = transform.position + Random.insideUnitSphere * spawnRadius;
|
||
|
spawnPoint.y = transform.position.y; // Adjust spawn height to match the spawner's y position
|
||
|
|
||
|
// Check for proximity to walls
|
||
|
if (!Physics.CheckSphere(spawnPoint, 0.3f, LayerMask.GetMask("Wall")))
|
||
|
{
|
||
|
validPlacement = true;
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (validPlacement)
|
||
|
{
|
||
|
GameObject newBox = Instantiate(boxPrefab, spawnPoint, Quaternion.identity);
|
||
|
currentBoxes.Add(newBox);
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
Debug.LogWarning("Failed to find a valid placement for the box after several attempts.");
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private void OnDrawGizmos()
|
||
|
{
|
||
|
Gizmos.color = Color.blue;
|
||
|
Gizmos.DrawWireSphere(transform.position, spawnRadius);
|
||
|
}
|
||
|
}
|
||
|
}
|