Skip to content

Instantly share code, notes, and snippets.

@khokhryakov47
Last active April 29, 2021 10:13
Show Gist options
  • Save khokhryakov47/db4589f3c9af404c5c3857743a6c6569 to your computer and use it in GitHub Desktop.
Save khokhryakov47/db4589f3c9af404c5c3857743a6c6569 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class ObectPool : MonoBehaviour
{
[SerializeField] private GameObject _container;
[SerializeField] private int _capacity;
private Camera _camera;
private List<GameObject> _pool = new List<GameObject>();
protected void Initialize(GameObject prefab)
{
_camera = Camera.main;
for (int i = 0; i < _capacity; i++)
{
GameObject spawned = Instantiate(prefab, _container.transform);
spawned.SetActive(false);
_pool.Add(spawned);
}
}
protected bool TryGetObject(out GameObject result)
{
result = _pool.FirstOrDefault(p => p.activeSelf == false);
return result != null;
}
protected void DisableObjectAbroadScreen()
{
Vector3 disablePoint = _camera.ViewportToWorldPoint(new Vector2(0, 0.5f));
foreach (var item in _pool)
{
if (item.activeSelf == true)
{
if (item.transform.position.x < disablePoint.x)
item.SetActive(false);
}
}
}
public void ResetPool()
{
foreach (var item in _pool)
{
item.SetActive(false);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment