I created a little pool in order to better manage my enemies, to which, an enemySpawner object calls to retrieve a clone and show it on screen
public class ObjectPool : MonoBehaviour
{
public static ObjectPool current;
public GameObject objectForPool;
public int poolAmmount = 20;
public bool growth = true;
List<GameObject> objectsForPool;
void Awake()
{
current = this;
}
// Use this for initialization
void Start ()
{
objectsForPool = new List<GameObject>();
for (int i = 0; i < poolAmmount; i++)
{
GameObject obj = Instantiate(objectForPool);
obj.SetActive(false);
objectsForPool.Add(obj);
}
}
public GameObject GetPooledObject()
{
for (int i = 0; i < objectsForPool.Count; i++)
{
if (!objectsForPool[i].activeInHierarchy)
{
return objectsForPool[i];
}
}
if (growth)
{
GameObject obj = Instantiate(objectForPool);
objectsForPool.Add(obj);
return obj;
}
return null;
}
// Update is called once per frame
void Update ()
{
}
}
The call(EnemySpawner update)
void Update ()
{
transform.position = new Vector3(transform.position.x + (speed * Time.deltaTime), 0, transform.position.z);
if (transform.position.x <= boundary.xMin || transform.position.x >= boundary.xMax)
speed *= -1;
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + spawnRate;
GameObject clone = GetComponent<ObjectPool>().GetPooledObject();
if (clone == null || clone.activeInHierarchy) return;
clone.GetComponent<EnemyMovement>().SetPlayerShip(playerShip);
clone.transform.position = transform.position;
clone.transform.rotation = transform.rotation;
clone.GetComponent<Health>().RestoreHealth();
clone.SetActive(true);
}
}
The problem here is, that my enemies are being deactivated on mid trajectory
I know my issue is in my pooling, but I can't figure out what I'm doing wrong