Any solution to omit Prefab conversion during runtime?

Hi guys,

Like all of you, I am using prefabs to preconfigure some of my entities. After that, I wrote an EntityPrefab custom implementation to automatically convert them via the custom GameObjectConversionSystem at runtime. And it works, but I feel like that could be optimized a bit and be converted at build time (you can check the warning from the learning course DOTS Best practices (Part 2, point 8 “Runtime data is not the same as authoring data”).

So, the question is, how could I achieve that?
Is it possible to convert those prefabs during build time (in editor it is okay to convert them in play mode, for now)?

Here is my custom implementation to do that with GameObjectConversionSystem:

EntityPrefab.cs

    [CreateAssetMenu(fileName = nameof(EntityPrefab), menuName = "ECS/" + nameof(EntityPrefab), order = 0)]
    public partial class EntityPrefab : SerializedScriptableObject
    {
        [OdinSerialize, NonSerialized] private GameObject _prefab;
        [OdinSerialize, NonSerialized] private string _prefabEntityName = string.Empty;
        private Entity _entity = Entity.Null;

        public GameObject Prefab => _prefab;
        public string PrefabEntityName => _prefabEntityName;

        // Keep in mind, that prefab is disabled by default
        public Entity Entity
        {
            get
            {
                if (_entity != Entity.Null)
                {
                    return _entity;
                }

                Debug.LogError($"PrefabEntity is NULL. Check {nameof(EntityPrefab)}({name}) registration in your {nameof(EntityPrefabsHolder)}", this);
                return Entity.Null;
            }
        }

        public void SetPrefabEntity(Entity entity)
        {
            Assert.AreNotEqual(entity, Entity.Null);
            _entity = entity;
        }
    }

EntityPrefabsHolder.cs

    [CreateAssetMenu(fileName = nameof(EntityPrefabsHolder), menuName = "ECS/" + nameof(EntityPrefabsHolder), order = 0)]
    public partial class EntityPrefabsHolder : SerializedScriptableObject
    {
        [AssetSelector(IsUniqueList = true, ExcludeExistingValuesInList = true)]
        [OdinSerialize, NonSerialized] private List<EntityPrefab> _entityPrefabs = new List<EntityPrefab>();

        public IReadOnlyList<EntityPrefab> EntityPrefabs => _entityPrefabs;

        private void OnValidate()
        {
#if UNITY_EDITOR
            Editor_OnValidate();
#endif // UNITY_EDITOR
        }
    }

DeclareEntityPrefabsGOCS.cs

    [UpdateInGroup(typeof(GameObjectDeclareReferencedObjectsGroup))]
    public partial class DeclareEntityPrefabsGOCS : GameObjectConversionSystem
    {
        private EntityPrefabsHolder _prefabsHolder;

        protected override void OnCreate()
        {
            base.OnCreate();

            // hack, cause could not get this conversion system in installer
            _prefabsHolder = ProjectContext.Instance.Container.Resolve<EntityPrefabsHolder>();
            Assert.IsNotNull(_prefabsHolder);
           
            var gameObjectExportGroup = World.CreateSystem<GameObjectExportGroup>();
            var assignPrimaryEntityToEntityPrefabGOCS = World.CreateSystem<AssignPrimaryEntityToEntityPrefabGOCS>();
           
            gameObjectExportGroup.AddSystemToUpdateList(assignPrimaryEntityToEntityPrefabGOCS);
        }
       
        protected override void OnUpdate()
        {
            _prefabsHolder.EntityPrefabs.ForEach(entityPrefab => DeclareReferencedPrefab(entityPrefab.Prefab));
        }
    }

AssignPrimaryEntityToEntityPrefabGOCS.cs

    public struct EntityPrefabContainer : IComponentData { }
   
    [DisableAutoCreation]
    [UpdateInGroup(typeof(GameObjectExportGroup))]
    public partial class AssignPrimaryEntityToEntityPrefabGOCS : GameObjectConversionSystem
    {
        private EntityPrefabsHolder _prefabsHolder; // could not Inject
        private Entity _entityPrefabContainer = Entity.Null;

        protected override void OnCreate()
        {
            base.OnCreate();

            // hack, cause could not get this conversion system in installer
            _prefabsHolder = ProjectContext.Instance.Container.Resolve<EntityPrefabsHolder>();
            Assert.IsNotNull(_prefabsHolder);
           
            Assert.AreEqual(_entityPrefabContainer, Entity.Null);
            _entityPrefabContainer = DstEntityManager.CreateEntity("EntityPrefabContainer" ,typeof(EntityPrefabContainer), typeof(Child), typeof(Prefab));
        }
       
        protected override void OnUpdate()
        {
            foreach (var entityPrefab in _prefabsHolder.EntityPrefabs)
            {
                var prefabEntity = GetPrimaryEntity(entityPrefab.Prefab);
                if (prefabEntity != Entity.Null)
                {
                    entityPrefab.SetPrefabEntity(prefabEntity);
                    if (!string.IsNullOrEmpty(entityPrefab.PrefabEntityName))
                    {
                        DstEntityManager.SetNameSafe(prefabEntity, entityPrefab.PrefabEntityName);
                    }

                    DstEntityManager.AddComponentData(prefabEntity, new Parent { Value = _entityPrefabContainer });
                    DstEntityManager.SetEnabled(prefabEntity, false);
                }
                else
                {
                    Debug.LogError($"Primary entity for prefab `{entityPrefab.name}` is NULL", entityPrefab);
                }
            }
        }
    }

Maybe look into subscenes. These can hold ‘pre-converted’ entities and skip the runtime conversion.

Thank you, @Arnold_2013 . I also thought about that but didn’t find any example or blogpost as a guide.

Guys, could you help me with that? I am sure, this problem is common for all of us and suggestions on how to handle that will be really useful!

@LaurentGibert , @mfuad , @elliotc-unity , @uDamian , @SteveM_Unity , @DreamingImLatios , @tim_jones , @cort_of_unity , @SteveSchefe ,

Subscenes are likely the correct answer, but I have never gotten them to work for anything other than rendering, Unity Physics, and a few IConvertGameObjectToEntity that read fully custom parameters and nothing from UnityEngine. I’m also not modifying packages like what Stunlock did, which might be part of my problem.

By the way, I don’t work for Unity.

@DreamingImLatios , yeah, I know. But you develop your own framework on top of DOTS. So for sure know more and deeper than me :slight_smile:

1 Like

For the DOTS animation package back in 0.17 it was required to load prefabs via subscene when using a build, otherwise no animation. For this purpose I created a Subscene with the animated prefabs in it. When the scene loads these prefabs make themselves known (a builder Entity with a component that stores their prefab entity and the enum value) and I store them in a NativeHashmap with the Enum as key. Then I need to instantiate an animated prefab I just make sure the spawner knows the enum value, to get the Prefab from the Hashmap.

Now even without the animation package working I still have this system in place, even though it is more complicated than just runtime converting the prefabs. Also the Hashmap is not filled at the first frame, so code that uses this hashmap first checks if its count is higher than 0.

Subscene are powerful for big worlds and what not… but that is too complicated for me… also when you unload a subscene all its entities disappear so you should make sure they did not follow the player :-).

To make a subscene just add it in the hierarchy with the “+” you can add an empty one and drag stuff into it, or you can select some stuff and create it from selection. You don’t need to include subscenes in the build settings, its not a ‘Scene’.

Example of the builder component which is on the entity in my subscene. The “prefab” is the actual entity I will call instantiate on. When the Builder entity is processed by the PrefabProcessSystem (the “prefab” is in the hashmap at “prefab Id”) the builder entity is destroyed, so it won’t try to re-add the same prefab the next frame.

Thank you. For now, this idea feels a bit complicated.

I would like to mimic a simple workflow with prefabs. Like, assign wherever prefab you want (or select via picker), just create EntityPrefab for the prefab (ideally, to create it at the time you assign prefab into a field). So, I would like to omit using subscenes if it’s possible.

At this stage, I am thinking about creating a master entity at editor time and serialize it on disk right away. Thus, on launch, I could load them all (even keep them loaded in the editor). The only thing is to link the loaded one to exact EntityPrefab (by path on disk or somehow).

This is just an idea, and for sure it might be impossible to implement. That is why it would be great to receive some guidance from DOTS team. I am sure they did some research in this area (or even have some implementation and I just miss it).

This is exactly what a subscene does. If you want to do it from a “Master Entity” its really easy. Create a component “allPrefabsComponent” with N entity fields one for each prefab you want to be able to access. Fill them in Editor with GameObject prefabs. Put the “Master Enity” GameObject with all these references into a Subscene and you are done (you need to save + close the subscene, but it has its own buttons for this).

Now you can use the TryGetSingleton() to get your master entity its allPrefabComponent and use its data to instantiate the prefabs.

It will only help for the startup time, and I would be surprised if you notice it at all, but now there is no runtime conversion needed for your prefabs.

1 Like

Yeah, you are right. Subscenes do precisely that. I don’t like the overall workflow with them — too many middlemen.

Artists also work with prefabs. They should not know how to handle a prefab. Ideally, just create one (or duplicate existing) and and assign where it should be used in a scriptable object (aka config).
Right now existing workflow is:

  • Create prefab
  • Via context menu select “Create EntityPrefab from Prefab”
  • Assign newly created EntityPrefab to a reference in ScriptableObject (that’s it for an artist)
  • [dev] And in code from EntityPrefab you just use Entity property that already contains MasterEntity (simply as is)

Not ideal, cause I would like to merge Steps 2 and 3 into one – assign a prefab (and do all technical stuff in the background). But for now, it works.

If it’s possible to do with subscenes – then it is worth trying.
Did I get you right and this is possible?:

  • Have a scene with a subscene and the holder for prefabs (as you suggested)
  • Via the context menu select “Create EntityPrefab from Prefab” to add the selected prefab to the holder
  • Save subscene (part of the context menu item)
  • [dev] In code somehow get MasterEntity by Prefab reference (need to achieve the same experience as it was in Step 4 of existing workflow)

NB. In my dreams I would also like to validate prefab reference for required authoring components (like RequireComponent attribute for MonoBehaviour), but that is a different story :slight_smile:

1 Like