Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Most efficient way to spawn objects

Discussion in 'Scripting' started by miszczyk, Jun 11, 2015.

  1. miszczyk

    miszczyk

    Joined:
    Sep 10, 2014
    Posts:
    8
    Hi,
    I found few threads about it, but answers were various and depended on specific cases, I couldn't find definitive answer, so I will ask in my exact matter.

    What's the most efficient way to spawn lots of enemies (10 - 15, 2d game, rig animated sprites) , mainly of the same type on mobile devices. I actually suffer a lot from heavy plugin i am forced to use in this project, and i heard a lot how heavy Instantiate method is. Is there any better way to spawn enemies? Possible ideas:

    1. Simply Instantate, and Destroy objects.
    2. Create array of GameObjects, Place them somewhere in scene, and active/deactive when not used
    3. Put objects somewhere outisde the camera view, and then change their position when needed, use them on scene, change position back outside of camera and pause movement.

    Another question:

    If i place 15 same prefabs on scene, and simply pause them, will they generate only one draw call? Will all added components be same heavy as when they animate, and transform?

    Components on enemies: Sprite Renderer, 2D Box Collider, Animator + Rig Animations, Rigibody 2D (for physic driven deaths), Scripts.

    Or maybe there is general answer for this type of question and i just couldn't find it?

    Thanks in advance for all your answers.
     
  2. MrPriest

    MrPriest

    Joined:
    Mar 17, 2014
    Posts:
    202
    Learn about pooling - it is useful in many cases - when an enemy dies, it will be removed from the game, but still be in the memory, and when you need another enemy spawn, that same enemy will return (just remember to change his location and HP, hehe...). That way your memory won't need to have any needless re-organization.
    As for the 2nd question - Think about it this way, every frame the entire screen is generated - so yes, it will get drawn every frame.
     
    NomadKing likes this.
  3. miszczyk

    miszczyk

    Joined:
    Sep 10, 2014
    Posts:
    8
    I've just watched whole unity live session about object pooling. It's great solution, thanks a lot for help!
     
  4. MrPriest

    MrPriest

    Joined:
    Mar 17, 2014
    Posts:
    202
    Glad I could help.