Skip to content

Instantly share code, notes, and snippets.

@muddokon
Created August 16, 2019 00:12
Show Gist options
  • Save muddokon/2fab12be54a1ca0aecb8dad0dfb40619 to your computer and use it in GitHub Desktop.
Save muddokon/2fab12be54a1ca0aecb8dad0dfb40619 to your computer and use it in GitHub Desktop.
Object Pool for Unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectPool : MonoBehaviour
{
[Header("Place here your objects to be spawned:")]
public GameObject[] objectsToSpawn;
private GameObject[] _objectsCollection;
[Header("Manage your spawns:")]
[Range(0.1f, 3f)]
public float minSpawnTime;
[Range(3.1f, 5f)]
public float maxSpawnTime;
public int poolSize;
private float _spawnTime;
private int _currentObject;
// Start is called before the first frame update
void Awake()
{
_spawnTime = calculateTime();
_objectsCollection = new GameObject[poolSize];
//llenar la pool
for (int i = 0; i < poolSize; i++)
{
var objToPlace = objectsToSpawn[Random.Range(0, objectsToSpawn.Length)];
var obj = Instantiate(objToPlace,transform.position,Quaternion.identity);
_objectsCollection[i] = obj;
}
//desactivarlos todos
foreach(GameObject go in _objectsCollection){
go.SetActive(false);
}
InvokeRepeating(nameof(SpawnObjects), _spawnTime, _spawnTime);
}
void SpawnObjects()
{
if (_currentObject >= poolSize)
_currentObject = 0;
var victimObject = _objectsCollection[_currentObject];
victimObject.SetActive(true);
victimObject.transform.position = transform.position;
_currentObject++;
}
float calculateTime()
{
return Random.Range(minSpawnTime, maxSpawnTime);
}
}
@KaJoseh
Copy link

KaJoseh commented Aug 23, 2019

Tysm my buddy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment