스파르타코딩클럽 게임개발

오늘은 스파르타 코딩 클럽 unity 게임 개발 과정 26일차(풀매니저와 스폰 )

코드천자문 2023. 12. 4. 09:49
반응형

몬스터를 많이 생성하고 싶다거나 플레이어 주변에 생성하고 싶을때 사용한다.

 

 

 

PoolManager

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PoolManager : MonoBehaviour
{
    // 미리 준비된 게임 오브젝트를 저장하는 변수
    public GameObject[] prefabs;

    // 풀을 관리하는 리스트
    List<GameObject>[] pools;

    private void Awake()
    {
        pools = new List<GameObject>[prefabs.Length];

        // 풀 초기화
        for (int i = 0; i < pools.Length; i++)
        {
            pools[i] = new List<GameObject>();
        }
    }

    public GameObject Get(int index)
    {
        GameObject select = null;

        // 선택한 풀에서 비활성화된 게임 오브젝트에 접근
        foreach (GameObject item in pools[index])
        {
            if (!item.activeSelf)
            {
                // 찾으면 select 변수에 할당하고 활성화 상태로 변경
                select = item;
                select.SetActive(true);
                break;
            }
        }

        // 찾지 못한 경우
        if (!select)
        {
            // 새로 생성하여 select 변수에 할당하고 풀에 추가
            select = Instantiate(prefabs[index], transform);
            pools[index].Add(select);
        }

        return select;
    }
}

Spawner

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spawner : MonoBehaviour
{
        public Transform[] spqwnPoint;
        public SpawnData[] spawnData;
        int level;
        float timer;

        private void Awake()
        {
                spqwnPoint = GetComponentsInChildren<Transform>();
        }
        // Update is called once per frame
        void Update()
        {
                //if (!GameManager.Instance.player.isLive) return;

                timer += Time.deltaTime;
                level = Mathf.Min(Mathf.FloorToInt(GameManager.Instance.stageLapseTime / 10f), spawnData.Length - 1);

                if (timer > spawnData[level].spawnTime)
                {
                        timer = 0;
                        Spawn();
                }
        }

        void Spawn()
        {
                GameObject monster = GameManager.Instance.poolManager.Get(0);
                monster.transform.position = spqwnPoint[Random.Range(1, spqwnPoint.Length)].position;
                monster.GetComponent<Monster>().Init(spawnData[level]);
        }
}

[System.Serializable]
public class SpawnData
{
        public int spriteType;
        public float spawnTime;
        public int health;
        public float speed;
}

 

플레이어에 빈 오브젝트를 단다(현재는 프리펩 상태라서 저렇게 보인다.)
그 아래에 빈 오브젝트를 생성하고 이름을 포인트라고 짓자.
포인트가 생성되었다.
복사하면 이렇게 된다.
이런식으로 플레이어를 둘러쌓듯이 만든다.
플레이어에 스크립트를 추가하고
풀매니저를 클릭
사용할 몬스터 프리펩을 넣는다.

 

스폰 데이터는 유니티에서 추가할 수 있다.
몬스터가 포인트에서 부터 나타난다.

반응형