Object pool with DOTS?

So I’m a nerd for optimisations and I’ve been looking into Unity’s new DOTS/ECS and I can certainly appreciate the boons it gives game developers. However, while I was able to implement a 3D pathfinding algorithm with it, I’m finding an object pool implementation to be a bit more complicated. While I can use NativeArray and/or NativeList, the complication comes when specifying a prefab, as the prefab is a GameObject reference and as far as I know, DOTS structs having any reference variables is a big no-no. That, or I can’t find anything akin to a weak ref container type. Any help would be appreciated, thanks!

NOTE: this answer is targetting entities 0.51 and won’t work with >=1.0

Start with familiarizing yourself with GameObject to Entity conversion workflow first. You may find out that’s instantiating from Entity prefabs is good enough:

using System.Collections.Generic;
using UnityEngine;
using Unity.Mathematics;
using Unity.Entities;
using Unity.Transforms;

public class HybridSpawner : MonoBehaviour
{

    Dictionary<GameObject,Entity> _prefabs = new Dictionary<GameObject,Entity>( capacity:100 );

    World _world;
    EntityManager _entityManager;
    BlobAssetStore _blobAssetStore;
    GameObjectConversionSettings _conversionSettings;

    void Start ()
    {
        _world = World.DefaultGameObjectInjectionWorld;
        _entityManager = _world.EntityManager;
        _blobAssetStore = new BlobAssetStore();
        _conversionSettings = GameObjectConversionSettings.FromWorld( _world , _blobAssetStore );
    }

    void OnDestroy ()
    {
        _blobAssetStore.Dispose();
    }

    public void Spawn ( GameObject prefab , Vector3 position , Quaternion rotation )
    {
        Entity entityPrefab = ToEntityPrefab( prefab );
        Entity instance = _entityManager.Instantiate( entityPrefab );
        _entityManager.SetComponentData( instance , new Translation{ Value = position } );
        _entityManager.SetComponentData( instance , new Rotation{ Value = rotation } );
    }

    public void Warmup ( GameObject prefab ) => ToEntityPrefab( prefab );

    Entity ToEntityPrefab ( GameObject prefab )
    {
        Entity entityPrefab;
        if( !_prefabs.TryGetValue( prefab , out entityPrefab ) )
        {
            entityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy( prefab , _conversionSettings );
            _prefabs.Add( prefab , entityPrefab );
        }
        return entityPrefab;
    }

}

Wow… I had to read that several times to sorta understand it.

A nice post that has some extra explanation in it! Unity: Object Pooling in ECS — Tri-Powered Games