- Home /
Object pooling?
Okay I understand object pooling saves performance such as creating a lot of objects. In my case, bullet holes (decals).
Is object pooling instantiating these decals and then positioning them when I need them? So the hierarchy would have a parent with 100 or so children of decals? Is that what I'm getting?
Answer by jmgek · Dec 22, 2014 at 05:18 AM
I don't fully understand your question, but I will explain what I think you are asking.
The idea of object pooling is to not create new memory on the machine to "Instanciate" A new object. You just take the already created object "Instanciated object" / Memory and re use it, in most cases you will just move it to a new place instead of destroying the old object and creating a new one. This is why it saves performance. So in your case when you shot your 100th bullet you should take your first decal and place it where your 100th bullet hits.
private Vector3 placePoolIs;
private int numberOfPoolCubes;
private List<GameObject> listOfPoolCubes = new List<GameObject>();
// Use this for initialization
void Start ()
{
placePoolIs = transform.position;
CreatePoolCubes();
}
void Update ()
{
transform.position = new Vector3(transform.position.x, Mathf.PingPong(Time.time, 1f) + 1.5f, transform.position.z);
if(listOfPoolCubes.Count > 0)
{
for (int i = 0; i < listOfPoolCubes.Count; i++)
{
listOfPoolCubes[i].transform.Translate(-Vector3.forward * Time.deltaTime);
if(listOfPoolCubes[i].transform.position.z < placePoolIs.z - 2f)
{
listOfPoolCubes[i].transform.position = Vector3.Lerp(listOfPoolCubes[i].transform.position, listOfPoolCubes[i].transform.position + new Vector3(0f,0f,10f), 0.5f);
}
}
}
}
void CreatePoolCubes()
{
for (int i = 0; i < 10; i++)
{
GameObject poolCube = GameObject.CreatePrimitive(PrimitiveType.Cube);
poolCube.name = "PoolCube" + numberOfPoolCubes;
listOfPoolCubes.Add(poolCube);
poolCube.transform.parent = transform;
poolCube.renderer.material.color = new Color(Random.Range(0f,1f),Random.Range(0f,1f),Random.Range(0f,1f));
poolCube.transform.localScale = new Vector3 (0.5f, 0.5f, 0.5f);
poolCube.transform.position = placePoolIs + new Vector3(0,0,i*0.5f);
numberOfPoolCubes++;
}
}
You can see I created a list of game objects and just kept moving them back to their starting position when they reached a spot.
Your answer
![](https://koobas.hobune.stream/wayback/20220613174633im_/https://answers.unity.com/themes/thub/images/avi.jpg)