Search Unity

Potential solution to improve GetComponent<> performance in my Generic Object Pooler

Discussion in 'Scripting' started by janimator, Jul 2, 2020.

  1. janimator

    janimator

    Joined:
    Apr 5, 2013
    Posts:
    52
    Here is what might be a silly question. I'm making my own generic object pool. Does it make sense at all to have a field of type Component to store the type of that inherited pool object? So literally store a reference to itself on itself. This is to avoid using GetComponent. so as an example:

    Code (CSharp):
    1.  
    2. public class PoolObject : MonoBehaviour{
    3.     public Component component;
    4.  
    5.     public override void SetGenericComponent()
    6.     {
    7.         component = this;
    8.     }
    9.  
    10.     public override  T GetGenericComponent<T>() where T : Component
    11.     {
    12.         if (component is T){
    13.            return component as T;
    14.         }
    15.     }
    16. }
    as apposed to just using typical
    GetComponent<>()

    So the grand idea would be to have an object pool that stores a queue of PoolObjects of all different types that inherit from PoolObject. Then when a pool object is requested I can pass in the type that it should be. The one caveat is that you need to guess what pool objects component should be. Please keep in mind while the examples below are stripped down, the ObjectPool class would be able to determine which pool object to grab to match the correct type.
    Code (CSharp):
    1.  
    2. // In Class requesting Pool Object
    3. SomeType obj = ObjectPool.GetGenericObj<SomeType>();
    4.  
    5. // In Object Pool
    6. public T GetGenericObj<T>() where T : Component
    7. {
    8.    // Some code to return the desired pool object
    9.    return poolObject.GetGenericComponent<T>();
    10. }
    11.  
    The alternative I imagine is just
    Code (CSharp):
    1.  
    2. // In Class requesting Pool Object
    3. SomeType obj = ObjectPool.GetObj().GetComponent<SomeType>();
    4.  
    The Object Pool would essentially return a PoolObject Cast as the requested type. The reason I'm jumping through hoops here is that it seems silly to always use GetComponent even though the pool object is always still in memory.
     
    Last edited: Jul 2, 2020
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,908
    If the caller knows the type such that they can provide the generic type T to your method they can just do the cast themselves. Not sure what GetComponent has to do with it. Nobody who understands components would use GetComponent<> just to cast a Component to it's concrete type.
     
  3. janimator

    janimator

    Joined:
    Apr 5, 2013
    Posts:
    52
    Ya I figured something was off with my thought process on this one. Back to the drawing board. Thanks for the help!