스파르타코딩클럽 게임개발
오늘은 스파르타 코딩 클럽 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;
}










반응형