Search Unity

Instantiating many different prefabs at run time.

Discussion in 'Scripting' started by aflesher, Jul 3, 2017.

  1. aflesher

    aflesher

    Joined:
    Dec 12, 2013
    Posts:
    28
    I'm working on a procedurally generated 2D game. All of the game objects are being loaded at run time. Currently I'm doing this by creating a prefab that acts as a look up table for all of the different game objects (i.e. an array of gameObjects that I assign all my prefabs to in the inspector.) Once the scene is loaded I destroy this lookup table gameObject.

    This seems to work pretty well but at the moment I have a pretty limited set of prefabs. I feel like this a recipe for unnecessary load times or memory problems because I am essentially getting a reference to every prefab that "could" be instantiated into a scene.

    Would it be better to use something like
    Code (CSharp):
    1. Resource.Load("folder/myPrefab");
    to get the prefabs as they are needed?
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
  3. daxiongmao

    daxiongmao

    Joined:
    Feb 2, 2016
    Posts:
    412
    You could think about using resource load. It is probably a better way if you really have lots of objects that won't be used.

    I would suggest splitting up the data you need to determine if an item is to be used.
    Bounds or properties, prefab path, etc. This could all be loaded.
    Then after generating your map you the do load resources on all the items actually used.

    I don't see much difference in having your prefab or scriptable object loading and releasing it.
    Compared to resources.loadall. This could actually be worse if you do not carefully manage your folders.

    You need to have an idea of your resources and budgets. If you have lots of items that use the same model and texture. Just in different configuration prefabs your not wasting much memory on gameobjects.
    If you have lots of different models and different textures. If you don't limit how you generate the level it doesn't really matter if you don't load all the prefabs first if you can end up generating a level with one of eveything any ways.

    In projects I am working on now I have smaller sets of things. I don't have a set of everything that could ever be.
    Because I won't generate a level like that. So my sets are of things that are based around themes or environments.
     
  4. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Consider using an asset bundle. It requires a little boiler plate to set up. But it has all of the indexing systems you need.