99 lines
2.6 KiB
C#
Raw Permalink Normal View History

2025-09-19 14:56:58 +05:00
using System.Collections.Generic;
using UnityEngine;
2025-09-19 19:43:49 +05:00
#if FUSION2
using Fusion;
#endif
2025-09-19 14:56:58 +05:00
namespace BulletHellTemplate
{
public class BoxSpawner : MonoBehaviour
{
[Header("Spawner Settings")]
2025-09-19 19:43:49 +05:00
public int maxBoxes = 5;
public float spawnCooldown = 5f;
public GameObject boxPrefab;
public float spawnRadius = 10f;
public LayerMask blockMask = 0;
2025-09-19 14:56:58 +05:00
2025-09-19 19:43:49 +05:00
[Header("Network")]
public bool useNetworkIfAvailable = true;
2025-09-19 14:56:58 +05:00
2025-09-19 19:43:49 +05:00
private readonly List<GameObject> currentBoxes = new();
private float cooldownTimer;
#if FUSION2
private NetworkRunner Runner =>
GameplaySync.Instance ? GameplaySync.Instance.Runner : null;
private bool NetActive =>
useNetworkIfAvailable &&
GameplaySync.Instance && GameplaySync.Instance.RunnerActive;
private bool IAmHost =>
NetActive && GameplaySync.Instance.IsHost;
#endif
void OnEnable() => cooldownTimer = spawnCooldown;
2025-09-19 14:56:58 +05:00
void Update()
{
2025-09-19 19:43:49 +05:00
if (GameplayManager.Singleton.IsPaused()) return;
#if FUSION2
if (NetActive && !IAmHost) return;
#endif
2025-09-19 14:56:58 +05:00
cooldownTimer -= Time.deltaTime;
2025-09-19 19:43:49 +05:00
currentBoxes.RemoveAll(go => !go);
if (cooldownTimer > 0f) return;
if (currentBoxes.Count >= maxBoxes)
{
cooldownTimer = spawnCooldown;
return;
}
2025-09-19 14:56:58 +05:00
2025-09-19 19:43:49 +05:00
if (TryGetSpawnPoint(out var pos))
2025-09-19 14:56:58 +05:00
{
2025-09-19 19:43:49 +05:00
#if FUSION2
if (NetActive)
{
var nob = Runner.Spawn(boxPrefab, pos, Quaternion.identity);
currentBoxes.Add(nob.gameObject);
}
else
#endif
{
var go = Instantiate(boxPrefab, pos, Quaternion.identity);
currentBoxes.Add(go);
}
2025-09-19 14:56:58 +05:00
}
2025-09-19 19:43:49 +05:00
cooldownTimer = spawnCooldown;
2025-09-19 14:56:58 +05:00
}
2025-09-19 19:43:49 +05:00
private bool TryGetSpawnPoint(out Vector3 spawnPoint)
2025-09-19 14:56:58 +05:00
{
2025-09-19 19:43:49 +05:00
for (int attempts = 0; attempts < 10; attempts++)
2025-09-19 14:56:58 +05:00
{
2025-09-19 19:43:49 +05:00
var p = transform.position + Random.insideUnitSphere * spawnRadius;
p.y = transform.position.y;
2025-09-19 14:56:58 +05:00
2025-09-19 19:43:49 +05:00
if (!Physics.CheckSphere(p, 0.3f, blockMask))
2025-09-19 14:56:58 +05:00
{
2025-09-19 19:43:49 +05:00
spawnPoint = p;
return true;
2025-09-19 14:56:58 +05:00
}
}
2025-09-19 19:43:49 +05:00
spawnPoint = Vector3.zero;
return false;
2025-09-19 14:56:58 +05:00
}
2025-09-19 19:43:49 +05:00
private void OnDrawGizmosSelected()
2025-09-19 14:56:58 +05:00
{
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(transform.position, spawnRadius);
}
}
}