Search Unity

Pooling GameObjects with same components but different values

Discussion in 'Scripting' started by aaversa, Jun 18, 2017.

  1. aaversa

    aaversa

    Joined:
    Sep 5, 2016
    Posts:
    41
    My 2D game has around 40-50 prefabs for things I call "Sprite Effects". These are things like explosions, splashes, and other such things that appear briefly (<1 second) and disappear. Right now I load all these resources into a string,GameObject dictionary and just Instantiate them... but obviously this becomes very heavy on CPU/GC.

    I understand the principles of GameObject pooling, but in this case, I'm not sure how to approach it. Each Sprite Effect has the same components (about 5, a mix of Unity and custom) but different values. One of the components is a custom Animation component which can have 100 values or more. (The component allows for lots of unique data per anim frame.)

    I figure one approach would be to create say 50 Sprite Effects at runtime with all the correct components but cleared values. Then at runtime, when I need to grab a specific Sprite Effect like "Fire Explosion", copy all of the component values from my dictionary to the selected pool object.

    The tricky thing there is that I have no easy way of copying over the component data... I guess I'd have to write custom functions for copying each component? Would copying over 100-150 values and doing a bunch of GetComponent<> calls end up cheaper than Instantiate?

    Another option I thought of was pooling specific effects, so I'd actually have 50x pools or whatever, starting with a handful of objects in each and expanding as needed. Is that overkill?

    Any advice appreciated!
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    Why not merge them all and have a script attached which changes the settings on the gameobject depending on what you want them to be?

    For example, you could have a init function which you call when you enable them and pass it an id which then does what you want. You only have to call getcomponent once for each component as you can store it in a variable and manipulate that.
     
  3. aaversa

    aaversa

    Joined:
    Sep 5, 2016
    Posts:
    41
    Each prefab has different values so there is no universal Init function that would make sense. I'm currently implementing the dictionary of pools and it seems like this is probably the way to go...