플레이어가 콜라이더 박스에 접근하면 몬스터 스폰, 최대치 도달하면 멈춤, 적 개체 죽으면 최대치까지 다시 증가.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class EnemySpawnBox_1 : MonoBehaviour
{
public string compareTag;
public UnityEvent onTriggerExitEvent;
public UnityEvent onTriggerStayEvent;
public bool enableSpawn = false;
public GameObject[] enemiesPrefabs;
private BoxCollider2D area;
public int enemyVisibleLimit;
public int enemySpawnLimit;
private List<GameObject> gameObjects = new List<GameObject>();
public void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.CompareTag(compareTag))
{
onTriggerExitEvent.Invoke();
enableSpawn = false;
}
}
public void OnTriggerStay2D(Collider2D collision)
{
if (collision.gameObject.CompareTag(compareTag))
{
onTriggerStayEvent.Invoke();
enableSpawn = true;
}
}
void Start()
{
area = GetComponent<BoxCollider2D>();
area.enabled = true;
InvokeRepeating("SpawnBox", 0, 2);
}
private Vector3 GetRandomPosition()
{
Vector3 basePosition = transform.position;
Vector3 size = area.size;
float posX = basePosition.x + Random.Range(-size.x / 2f, size.x / 2f);
float posY = basePosition.y + Random.Range(-size.y / 2f, size.y / 2f);
float posZ = basePosition.z + Random.Range(-size.z / 2f, size.z / 2f);
Vector3 spawnPos = new Vector3(posX, posY, posZ);
return spawnPos;
}
private void SpawnBox()
{
if (enableSpawn)
{
Collider2D[] colliders = Physics2D.OverlapBoxAll(transform.position, area.size, 0);
int enemyCount = 0;
foreach (Collider2D collider in colliders)
{
if (collider.CompareTag("Player"))
{
enemyCount++;
}
}
if (enemyCount < enemyVisibleLimit && gameObjects.Count < enemySpawnLimit)
{
int selection = Random.Range(0, enemiesPrefabs.Length);
GameObject selectedPrefab = enemiesPrefabs[selection];
Vector3 spawnPos = GetRandomPosition();
GameObject instance = Instantiate(selectedPrefab, spawnPos, Quaternion.identity);
gameObjects.Add(instance);
}
}
else
{
// If spawning is disabled, remove all the spawned objects from the list
gameObjects.RemoveAll(obj => obj == null);
}
}
}
'유니티 공부' 카테고리의 다른 글
레벨업 RPG 리그리마 1.101 ver 업데이트 (0) | 2023.03.20 |
---|---|
적 죽을때 경험치와 랜덤 아이템 드랍 코드 (0) | 2023.02.07 |
OnColliderOrTriggerEvent (0) | 2023.01.27 |
이동하는 발판용(Moving Block) 코드 (1) | 2023.01.12 |