How to convert a prefab into an entity prefab at runtime?

Right now, we place all our prefabs in a subscene and have them converted using GetEntity(). But this may now be untenable since we have a lot of prefabs and we don’t necessarily use all of them in a single session (say iteration). Is there a way to do the conversion at runtime like only when they are needed? I’ve searched about this and I don’t get a clear answer.

Or am I worrying too much and that converting loads of prefabs is relatively cheap?

Sadly, the only way to bake prefab entities is referencing them in a sub-scene like you did.

Or am I worrying too much and that converting loads of prefabs is relatively cheap?

In the editor, yes conversion can be slow. In a built player, there is no conversion : The sub-scene is already baked & optimized for fast loading.

Is there a way to do the conversion at runtime like only when they are needed?

Nope, at least not using the subscene/baking workflow.

I’d like to elaborate but could you confirm that you when you are saying “entity prefab”, you are talking about a “template” entity to feed into a spawner for example?

Yes? I mean here the entity that is returned when using GetEntity() on prefab in the baker. This is then used in EntityManager.Instantiate() or ECB.Instantiate().

How about memory usage? Since the subscene is loaded at the start, is the memory required to load those prefabs already taken?

If the “Auto Load Scene” field of the Sub Scene component is checked, Unity will automatically stream the subscene (and allocate its memory) AFTER the game object scene containing it is loaded.

If you want more control you can uncheck “Auto Load Scene” and do it manually using the SceneSystem API.

If you want to even more control & load each prefab manually, you can use EntityPrefabReference (look in Baking Prefabs). Each EntityPrefabReference will be baked in it’s own subscene, and you load them either using RequestEntityPrefabLoaded or SceneSystem.LoadPrefabAsync.

Be careful, it doesn’t work in blob assets… EntityPrefabReference must be present in an baked entity component to trigger the prefab baking.

Sadly, there is no grouping/dependency tracking like the addressable package, you’ll have to create your own systems to load ce necessary prefab entities before using them.

2 Likes

I see. That’s cool. Thank you very much.