- Home /
Duplicate Question
What's the easiest way to create an Instance Manager as to avoid calling Instantiate during game runtime?
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?
this is just called having a "pool" -- if you invented this yourself, well done because it's a basic in video games !!! well done
http://answers.unity3d.com/questions/321762/how-to-assign-variable-to-a-prefabs-child.html
pls vote up my essay there as I desperately need moar points
"I also was told [...] you must use a pooling system." I suspect that if you dig, than that guy heard it from a friend of his cousin. I Instantiate on an iPad like ... well, someone who instantiates a lot ... and it's fine. Threw in an object pool (for those darn non-autodestructing shuriken PEs) and didn't see a difference.
If you spawn and destroy a lot (20+ items/second?) and that's giving the game hiccups, then, sure, managing your own object pool might help. Pools are an operating systems concept, if you want to look up the source material on them.
Answer by Diet-Chugg · May 25, 2013 at 07:57 AM
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.