Search Unity

  1. Get the latest news, tutorials and offers directly to your inbox with our newsletters. Sign up now.
    Dismiss Notice

Resolved Question About Object Pooling Components

Discussion in 'Scripting' started by PaperMouseGames, Mar 12, 2021.

  1. PaperMouseGames

    PaperMouseGames

    Joined:
    Jul 31, 2018
    Posts:
    257
    I'm following this Brakeys tutorial on object pooling:



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

    Code (CSharp):
    1. private void Start()
    2.     {
    3.         poolDictionary = new Dictionary<string, Queue<PooledUIObject>>();
    4.  
    5.         foreach (UIPool pool in pools)
    6.         {
    7.             Queue<PooledUIObject> objectPool = new Queue<PooledUIObject>();
    8.  
    9.             for (int i = 0; i < pool.size; i++)
    10.             {
    11.                 GameObject obj = Instantiate(pool.pooledObject.gameObject, this.transform);
    12.  
    13.                 PooledUIObject pooledObject = obj.GetComponent<PooledUIObject>();
    14.  
    15.                 pooledObject.gameObject.SetActive(false);
    16.                 objectPool.Enqueue(pooledObject);
    17.             }
    18.  
    19.             poolDictionary.Add(pool.tag, objectPool);
    20.         }
    21.     }
    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?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    5,690
    Instead of calling Instantiate like this:
    Code (CSharp):
    1. GameObject obj = Instantiate(pool.pooledObject.gameObject, this.transform);
    Can you call it like this?
    Code (CSharp):
    1. PooledUIObject pooledObject = Instantiate(pool.pooledObject, this.transform);
     
    Joe-Censored and PaperMouseGames like this.
  3. PaperMouseGames

    PaperMouseGames

    Joined:
    Jul 31, 2018
    Posts:
    257
    Thanks perfect, thank you! For some reason I was under the impression that Instantiate always returned GameObjects. Thanks again!
     
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,090
    Does this actually save the performance cost of GetComponent, or does it just call GetComponent under the hood?
     
  5. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    5,690
    Probably just calls it under the hood. But the performance cost of GetComponent is overblown anyway.
     
    PaperMouseGames and Joe-Censored like this.
unityunity