유니티 공부

몬스터 생성 박스 콜라이더

원티어맨 2023. 3. 2. 00:51

 

플레이어가 콜라이더 박스에 접근하면 몬스터 스폰, 최대치 도달하면 멈춤, 적 개체 죽으면 최대치까지 다시 증가.

 

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);
        }
    }
}