71 lines
1.8 KiB
C#
71 lines
1.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class ChipPool : MonoBehaviour
|
|
{
|
|
private Chip _prefab;
|
|
private Queue<Chip> _availableChips;
|
|
private bool _isInit;
|
|
|
|
public static ChipPool Instance { get; private set; }
|
|
|
|
public void Init(Chip prefab, int amount)
|
|
{
|
|
if (_isInit)
|
|
return;
|
|
|
|
_prefab = prefab;
|
|
_availableChips = new Queue<Chip>(amount);
|
|
|
|
for (int i = 0; i < amount; i++)
|
|
Create();
|
|
|
|
Instance = this;
|
|
_isInit = true;
|
|
}
|
|
|
|
public Chip Get()
|
|
{
|
|
if (_isInit == false)
|
|
throw new InvalidOperationException("Пул фишек не инициализирован");
|
|
|
|
if (_availableChips.Count == 0)
|
|
Create();
|
|
|
|
Chip chip = _availableChips.Dequeue();
|
|
chip.transform.SetParent(null);
|
|
chip.gameObject.SetActive(true);
|
|
return chip;
|
|
}
|
|
|
|
public Chip GetConfigured(Sprite sprite, Team team)
|
|
{
|
|
if (_isInit == false)
|
|
throw new InvalidOperationException("Пул фишек не инициализирован");
|
|
|
|
Chip chip = Get();
|
|
chip.Configure(sprite, team);
|
|
return chip;
|
|
}
|
|
|
|
public void Release(Chip chip)
|
|
{
|
|
if (_isInit == false)
|
|
throw new InvalidOperationException("Пул фишек не инициализирован");
|
|
|
|
chip.gameObject.SetActive(false);
|
|
chip.transform.rotation = Quaternion.identity;
|
|
chip.transform.SetParent(transform);
|
|
_availableChips.Enqueue(chip);
|
|
}
|
|
|
|
private Chip Create()
|
|
{
|
|
Chip chip = Instantiate(_prefab, transform);
|
|
chip.gameObject.SetActive(false);
|
|
_availableChips.Enqueue(chip);
|
|
|
|
return chip;
|
|
}
|
|
} |