I am programming for mobile, and am told that Instantiate is an expensive operation. I also was told to avoid this, you must use a pooling system, where objects that would be instantiated are created at game start and added to an available pool off screen (where they are disabled and awake, start, etc are not called) and then activated and moved when they are needed, and removed from the available pool. Then when the gameobject has served its purpose, it is deactivated and moved back into the pool, off screen.
What is the best way to implement this, in the respect of efficiency and complexity to use in game code?
Here’s a script that I used for this which has a couple more features than you need and
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class GameObjectPool : MonoBehaviour
{
public GameObject[] pool;
public GameObject Drop()
{
foreach(GameObject drop in pool)
{
if(!drop.activeInHierarchy)
{
drop.SetActive(true);
return drop;
}
}
return null;
}
public GameObject[] GetActiveInPool()
{
List<GameObject> actives = new List<GameObject>();
foreach(GameObject drop in pool)
{
if(drop.activeInHierarchy)
actives.Add(drop);
}
return actives.ToArray();
}
public GameObject[] GetDroppables()
{
List<GameObject> droppables = new List<GameObject>();
foreach(GameObject drop in pool)
{
if(!drop.activeInHierarchy)
droppables.Add(drop);
}
return droppables.ToArray();
}
}
Just fill the array with in-active objects.
In other scrips call the Drop() function on this component which will give you an object from the pool that’s inactive (if there is one)
the game object you get will still be where it originally was but you can move that object wherever you want by changing it’s transform.position. It’s proved to be plenty efficient for me. Just check to make sure the object you get from Drop() isn’t null.