50 lines
1.5 KiB
C#
50 lines
1.5 KiB
C#
using System.Collections.Generic;
|
|
using Enums;
|
|
using Services.Interfaces;
|
|
using UnityEngine;
|
|
using Views;
|
|
using Object = UnityEngine.Object;
|
|
|
|
namespace Services {
|
|
public class ObjectPoolService:IObjectPool<GemView> {
|
|
private readonly GemView[] prefabs;
|
|
private readonly Transform parent;
|
|
|
|
private readonly Stack<GemView> pool = new Stack<GemView>();
|
|
|
|
public ObjectPoolService(GemView[] prefabs, Transform parent) {
|
|
this.prefabs = prefabs;
|
|
this.parent = parent;
|
|
}
|
|
|
|
public GemView Get(GemType type, Vector2Int position, float dropHeight) {
|
|
int typeAsInt = (int) type;
|
|
|
|
GemView gemView;
|
|
float randomOffset = Random.Range(1f, 2.5f);
|
|
Vector2 vector2Position = new Vector2(position.x, position.y + dropHeight * randomOffset);
|
|
if (this.pool.Count > 0) {
|
|
gemView = this.pool.Pop();
|
|
|
|
|
|
gemView.transform.localPosition = vector2Position;
|
|
return gemView;
|
|
}
|
|
|
|
gemView = Object.Instantiate(this.prefabs[typeAsInt], vector2Position, Quaternion.identity, this.parent);
|
|
return gemView;
|
|
}
|
|
|
|
public void Release(GemView gemView) {
|
|
if (gemView == null)
|
|
return;
|
|
|
|
gemView.gameObject.SetActive(false);
|
|
this.pool.Push(gemView);
|
|
}
|
|
|
|
public void Clear() {
|
|
this.pool.Clear();
|
|
}
|
|
}
|
|
} |