질문 원본 글 : 적들 랜덤 스폰 질문이요. - 인디 게임 개발 마이너 갤러리 (dcinside.com)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class EnemySpawner : MonoBehaviour
{
    public string compareTag;
    public UnityEvent onTriggerExitEvent;
    public UnityEvent onTriggerStayEvent;
    public bool enableSpawn = false;
    public GameObject[] enemiesprefabs;
    private BoxCollider2D area;
    // 동시 적 스폰 갯수
    int enemyVisibleLimit;
    // 최대 적 스폰 갯수
    int enemySpawnLimit;
    // 생성된 객체를 받아올 배열
    public GameObject[] enemyclonelist;
    private new List<GameObject> gameObject = 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;
        // 적 스폰 관련 값 초기화
        enemyVisibleLimit = 2;
        enemySpawnLimit = 10;
        InvokeRepeating("Spawn"02);
    }
    private Vector3 GetRandomPosition()
    {
        //Vector3 basePosition = transform.position; -> offset값까지 추가 계산
        Vector3 basePosition = transform.position + new Vector3(area.offset.x, area.offset.y);
        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 Spawn()
    {
        if (enableSpawn)
        {
            //// Prefub의 태그를 이용해서 적 갯수 찾아오기
            //enemyclonelist = GameObject.FindGameObjectsWithTag("Enemy");
            // -> area를 캐스팅한 결과값에서만 적 갯수 찾아오기
            var rayhits = Physics2D.BoxCastAll((Vector2)area.transform.position + area.offset, area.size, 0, Vector2.one, 0);
            List<GameObject> enemylist = new List<GameObject>();
            foreach (var obj in rayhits)
            {
                if (obj.transform.CompareTag(compareTag))
                    enemylist.Add(obj.transform.gameObject);
            }
            enemyclonelist = enemylist.ToArray();
            if (enemyclonelist.Length < 5)
            {
                int selection = Random.Range(0, enemiesprefabs.Length);
                GameObject selectedPrefab = enemiesprefabs[selection];
                Vector3 spawnPos = GetRandomPosition();//랜덤위치함수
                GameObject instance = Instantiate(selectedPrefab, spawnPos, Quaternion.identity);
                gameObject.Add(instance);
            }
            //  else  if(enemyclonelist.Length >= 5) { enableSpawn = false;}
        }
    }
}
cs




최대한 기존 코드에서 덜 손봤음


단순히 area.Cast()로도 영역의 적들 검색이 가능한데 그 경우 이 스포너의 오브젝트가 rigidbody2d가 필요하기 때문에


혹시 몰라 그냥 Physics2d의 캐스트를 사용함



대충 잘되는것 같음


나한테 대댓글 단게 아니라 원본 글의 댓글로 코드 요청해서 내가 늦게봄