Created
August 16, 2019 00:12
-
-
Save muddokon/2fab12be54a1ca0aecb8dad0dfb40619 to your computer and use it in GitHub Desktop.
Object Pool for Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tysm my buddy