Question About Object Pooling Components

I’m following this Brakeys tutorial on object pooling:

And here is what my method that initially instantiates the objects looks like:

private void Start()
    {
        poolDictionary = new Dictionary<string, Queue<PooledUIObject>>();

        foreach (UIPool pool in pools)
        {
            Queue<PooledUIObject> objectPool = new Queue<PooledUIObject>();

            for (int i = 0; i < pool.size; i++)
            {
                GameObject obj = Instantiate(pool.pooledObject.gameObject, this.transform);

                PooledUIObject pooledObject = obj.GetComponent<PooledUIObject>();

                pooledObject.gameObject.SetActive(false);
                objectPool.Enqueue(pooledObject);
            }

            poolDictionary.Add(pool.tag, objectPool);
        }
    }

It’s all working well, but I’m wondering, is there any way to avoid the GetComponent call when doing something like this?

I want the PooledUIObject component because that holds the text and image that I want to have access to but when I instantiate something it always just returns a GameObject, so is there any way, using this object pooling technique, to avoid the (potentially hundreds) GetComponent calls?

Instead of calling Instantiate like this:

GameObject obj = Instantiate(pool.pooledObject.gameObject, this.transform);

Can you call it like this?

PooledUIObject pooledObject = Instantiate(pool.pooledObject, this.transform);
2 Likes

Thanks perfect, thank you! For some reason I was under the impression that Instantiate always returned GameObjects. Thanks again!

Does this actually save the performance cost of GetComponent, or does it just call GetComponent under the hood?

Probably just calls it under the hood. But the performance cost of GetComponent is overblown anyway.

2 Likes