Home > Software engineering >  Unity adding prefabs on runtime
Unity adding prefabs on runtime

Time:10-01

I'm very new to Unity and have a question regarding loading of game objects at runtime. I have only 4 scenes (4 different 'surroundings'). Each of them displays a 3D object - the one that the user selects from the menu. There will be around 60 3D objects (but only one at a time is displayed). How to deal with loading them? I don't want to create 60 × 4 scenes and add them as a prefab to a scene individually, but keep only 4 scenes and programmatically add 3D objects to them to the scene. What is the best practice memory & performance wise? Can they be reused? How to approach this problem if objects are very big? Are there any code samples?

CodePudding user response:

I’m far from being an expert but the way I have done it is with instantiate.

Practically you generate from a prefab a gameObject and later (if it isn’t needed anymore) you Destroy(gameObject);

Instantiate(prefab, new Vector3(x, y, z), Quaternion.identity);

CodePudding user response:

You can have a script on each scene, referencing 60 prefabs (there's an easy trick to it - if have a public List and want to drag multiple objects from the project window, just lock your inspector using a padlock, you can then select multiple prefabs in the project window and drag them all in one move, releasing on the NAME of the list, instead of expanded empty field).

Prefabs are shared within a project so they won't get duplicated between scenes.

You could also have them all on the scene to start with, deactivated, and just activate one selected prefab, this will be slightly easier, but will use more memory, in terms of build size this should make no difference. If the objects are big you are probably better of instantiating and destroying them as you go

  • Related