using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class PoolInfo
{
public string name;
public GameObject prefab;
public int amount;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pool
{
public Transform root { get; protected set; }
public GameObject prefab { get; protected set; }
protected Queue<GameObject> objects = new Queue<GameObject>();
public Pool(Transform wantRoot, GameObject wantPrefab)
{
root = wantRoot;
prefab = wantPrefab;
}
public GameObject Create()
{
GameObject target;
if (objects.Count <= 0)
{
CreateNewInstance();
}
target = objects.Dequeue();
target.SetActive(true);
target.BroadcastMessage("PoolInitialize");
return target;
}
public GameObject CreateNewInstance()
{
GameObject inst = GameObject.Instantiate(prefab, root);
PoolComponent poolCompo = inst.GetComponent<PoolComponent>();
if(poolCompo == null)
{
poolCompo = inst.AddComponent<PoolComponent>();
}
poolCompo.myPool = this;
inst.SetActive(false);
objects.Enqueue(inst);
return inst;
}
public void Delete(GameObject target)
{
target.SetActive(false);
objects.Enqueue(target);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PoolManager : MonoBehaviour
{
public PoolInfo[] infos;
static Dictionary<string, Pool> poolDictionary = new Dictionary<string, Pool>();
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
Create("공").transform.position = Random.insideUnitSphere * 5;
}
if (Input.GetKeyDown(KeyCode.S))
{
Create("큐브").transform.position = Random.insideUnitSphere * 5;
}
if(Input.GetMouseButtonDown(0))
{
Ray cameraRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Physics.Raycast(cameraRay, out hit);
if (hit.collider != null)
{
Delete(hit.collider.gameObject);
}
}
}
void Start()
{
Load();
}
public static void Delete(GameObject target)
{
PoolComponent poolCompo = target.GetComponent<PoolComponent>();
if(poolCompo)
{
Pool targetPool = poolCompo.myPool;
if(targetPool != null)
{
targetPool.Delete(target);
}
else
{
Destroy(target);
}
}
else
{
Destroy(target);
}
}
public static GameObject Create(string wantName)
{
Pool targetPool;
if(poolDictionary.TryGetValue(wantName, out targetPool))
{
return targetPool.Create();
}
return null;
}
public void Load()
{
foreach(var current in infos)
{
Pool currentPool = new Pool(new GameObject(current.name).transform, current.prefab);
poolDictionary.Add(current.name, currentPool);
for(int i = 0; i < current.amount; i++)
{
currentPool.CreateNewInstance();
}
}
}
}