Create ObjectPoolService
This commit is contained in:
8
Assets/Scripts/Services/Interfaces.meta
Normal file
8
Assets/Scripts/Services/Interfaces.meta
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 89ba33c34f0301d4fbe4d0a614d2da9a
|
||||||
|
folderAsset: yes
|
||||||
|
DefaultImporter:
|
||||||
|
externalObjects: {}
|
||||||
|
userData:
|
||||||
|
assetBundleName:
|
||||||
|
assetBundleVariant:
|
||||||
8
Assets/Scripts/Services/Interfaces/IObjectPool.cs
Normal file
8
Assets/Scripts/Services/Interfaces/IObjectPool.cs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
namespace Services.Interfaces {
|
||||||
|
public interface IObjectPool<T> where T : class {
|
||||||
|
T Get();
|
||||||
|
void Fill();
|
||||||
|
void Release(T gameObject);
|
||||||
|
void Clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
3
Assets/Scripts/Services/Interfaces/IObjectPool.cs.meta
Normal file
3
Assets/Scripts/Services/Interfaces/IObjectPool.cs.meta
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 8cda63dc65b2425b810a008823083079
|
||||||
|
timeCreated: 1765625964
|
||||||
38
Assets/Scripts/Services/ObjectPoolService.cs
Normal file
38
Assets/Scripts/Services/ObjectPoolService.cs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
using System.Collections;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Services.Interfaces;
|
||||||
|
using UnityEngine;
|
||||||
|
|
||||||
|
namespace Services {
|
||||||
|
public class ObjectPoolService:IObjectPool<GameObject> {
|
||||||
|
private readonly GameObject prefab;
|
||||||
|
private readonly Transform parent;
|
||||||
|
private readonly int size;
|
||||||
|
|
||||||
|
private readonly Stack<GameObject> pool = new Stack<GameObject>();
|
||||||
|
|
||||||
|
public ObjectPoolService(GameObject prefab, Transform parent, int size = 5) {
|
||||||
|
this.prefab = prefab;
|
||||||
|
this.parent = parent;
|
||||||
|
this.size = size;
|
||||||
|
}
|
||||||
|
|
||||||
|
public GameObject Get() {
|
||||||
|
return this.pool.Count == 0 ? Object.Instantiate(this.prefab, this.parent) : this.pool.Pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Fill() {
|
||||||
|
for (int i = 0; i < this.size; i++) {
|
||||||
|
Object.Instantiate(this.prefab, this.parent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Release(GameObject gameObject) {
|
||||||
|
this.pool.Push(gameObject);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Clear() {
|
||||||
|
this.pool.Clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
3
Assets/Scripts/Services/ObjectPoolService.cs.meta
Normal file
3
Assets/Scripts/Services/ObjectPoolService.cs.meta
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
fileFormatVersion: 2
|
||||||
|
guid: 531f947d214849c99d3c09ae404406d6
|
||||||
|
timeCreated: 1765625414
|
||||||
Reference in New Issue
Block a user