88 lines
2.7 KiB
C#
88 lines
2.7 KiB
C#
using UnityEngine;
|
|
|
|
public class MonsterSpawner : MonoBehaviour
|
|
{
|
|
[Header("--- 몹 스폰 설정 ---")]
|
|
[SerializeField] private string mobTag = "NormalMob"; // 풀에 등록된 태그명
|
|
[SerializeField] private float spawnRange = 15f; // 플레이어 감지 범위
|
|
[SerializeField] private float respawnCooldown = 3f; // 몹 사망 시 재소환 대기 시간
|
|
|
|
private GameObject _myMonster;
|
|
private MonsterClass _monsterScript;
|
|
private Transform _player;
|
|
private float _nextSpawnTime;
|
|
|
|
private void Start()
|
|
{
|
|
FindPlayer();
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
// ⭐ [안전장치] 플레이어를 못 찾았다면 계속 다시 찾습니다.
|
|
if (_player == null)
|
|
{
|
|
FindPlayer();
|
|
return;
|
|
}
|
|
|
|
float dist = Vector3.Distance(transform.position, _player.position);
|
|
|
|
// 1. 플레이어가 범위 안에 들어왔을 때
|
|
if (dist <= spawnRange)
|
|
{
|
|
// 쿨타임이 지났고, 현재 관리하는 몹이 없을 때만 소환
|
|
if (Time.time >= _nextSpawnTime && (_myMonster == null || !_myMonster.activeSelf))
|
|
{
|
|
SpawnMonster();
|
|
}
|
|
}
|
|
// 2. 플레이어가 범위 밖으로 나갔을 때 (회색 점 상태로 회수)
|
|
else
|
|
{
|
|
DespawnMonster();
|
|
}
|
|
}
|
|
|
|
private void FindPlayer()
|
|
{
|
|
GameObject playerObj = GameObject.FindGameObjectWithTag("Player");
|
|
if (playerObj != null) _player = playerObj.transform;
|
|
}
|
|
|
|
private void SpawnMonster()
|
|
{
|
|
// 제네럴 오브젝트 풀에서 몹을 빌려옵니다.
|
|
_myMonster = GenericObjectPool.Instance.SpawnFromPool(mobTag, transform.position, transform.rotation);
|
|
|
|
if (_myMonster != null)
|
|
{
|
|
_monsterScript = _myMonster.GetComponent<MonsterClass>();
|
|
}
|
|
}
|
|
|
|
private void DespawnMonster()
|
|
{
|
|
if (_myMonster != null && _myMonster.activeSelf)
|
|
{
|
|
// 몹이 살아있는 상태에서 멀어진 거라면 즉시 회수
|
|
if (_monsterScript != null && !_monsterScript.IsDead)
|
|
{
|
|
_myMonster.SetActive(false);
|
|
_nextSpawnTime = Time.time; // 멀어진 건 즉시 재생성 대기
|
|
}
|
|
// 몹이 죽어서 사라진 거라면 지정된 쿨타임 적용
|
|
else if (_monsterScript != null && _monsterScript.IsDead)
|
|
{
|
|
_nextSpawnTime = Time.time + respawnCooldown;
|
|
}
|
|
}
|
|
}
|
|
|
|
// 에디터에서 스폰 범위를 시각적으로 확인
|
|
private void OnDrawGizmosSelected()
|
|
{
|
|
Gizmos.color = Color.red;
|
|
Gizmos.DrawWireSphere(transform.position, spawnRange);
|
|
}
|
|
} |