SummerGame/Assets/_Project/Scripts/RunnerPart/Traffic/TrafficPool.cs

78 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.Generic;
using UnityEngine;
public class TrafficPool : MonoBehaviour
{
public static TrafficPool Instance { get; private set; }
[System.Serializable]
public class PoolEntry
{
public GameObject prefab;
public int size;
}
[Header("Настройки пула")]
public List<PoolEntry> poolEntries;
private Dictionary<GameObject, Queue<TrafficCar>> _poolDictionary;
void Awake()
{
if (Instance == null) Instance = this;
else Destroy(gameObject);
_poolDictionary = new Dictionary<GameObject, Queue<TrafficCar>>();
foreach (var entry in poolEntries)
{
Queue<TrafficCar> objectPool = new Queue<TrafficCar>();
for (int i = 0; i < entry.size; i++)
{
GameObject car = Instantiate(entry.prefab, transform);
car.transform.rotation = Quaternion.identity;
car.SetActive(false);
TrafficCar carComponent = car.GetComponent<TrafficCar>();
carComponent.originalPrefab = entry.prefab;
objectPool.Enqueue(carComponent);
}
_poolDictionary.Add(entry.prefab, objectPool);
}
}
public TrafficCar GetCar()
{
if (poolEntries.Count == 0) return null;
PoolEntry randomEntry = poolEntries[Random.Range(0, poolEntries.Count)];
Queue<TrafficCar> carQueue = _poolDictionary[randomEntry.prefab];
if (carQueue.Count == 0)
{
Debug.LogWarning($"Пул для {randomEntry.prefab.name} пуст!");
return null;
}
TrafficCar car = carQueue.Dequeue();
return car;
}
public void ReturnCar(TrafficCar car)
{
if (car.originalPrefab != null && _poolDictionary.ContainsKey(car.originalPrefab))
{
car.gameObject.SetActive(false);
_poolDictionary[car.originalPrefab].Enqueue(car);
}
else
{
Debug.LogWarning($"Не удалось вернуть машину {car.name} в пул. Уничтожение...");
Destroy(car.gameObject);
}
}
}