Memory leak during creation of an entity prefab

I’m trying to learn DOTS from an online tutorial.

The intent is to take in GameObject prefab, turn it into entity prefab and then create any needed entities from that prefab. It ends with three same errors: “A Native Collection has not been disposed, resulting in a memory leak. Enable Full StackTraces to get more details.”, nothing else, double-clicking does nothing. Googling it shows that it happens to people in relation to analytics, but I have none, its turned off.

If executeOnStart is false, this error doesn’t happen. This script is attached to the GameObject:

public class PrefabSpawner : MonoBehaviour
{

    public bool executeOnStart;
    [SerializeField] GameObject gameObjectPrefab; // fails on anything, null, standard unity shape or a model.
    Entity entityPrefab;
    World defaultWorld;
    EntityManager entityManager;

    void Start()
    {
        defaultWorld = World.DefaultGameObjectInjectionWorld;
        entityManager = defaultWorld.EntityManager;
        if (executeOnStart) DoIt();
    }

    void DoIt()
    {
        EntityArchetype archetype = entityManager.CreateArchetype(
            typeof(Translation),
            typeof(Rotation),
            typeof(RenderMesh),
            typeof(RenderBounds),
            typeof(LocalToWorld)
        );
          
        var settings = GameObjectConversionSettings.FromWorld(defaultWorld, new BlobAssetStore());
        entityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(gameObjectPrefab, settings);

        // Create 100 copies
        for (var i = 0; i < 100; i++)
        {
            Entity myEntity = entityManager.Instantiate(entityPrefab);
            entityManager.SetComponentData(myEntity, new Translation
            {
                Value = new float3(5, 10, 15)
            });
        }
    }
}

Have you any other system in your project?
It looks like you have NativeArray somewhere, which is not disposed.

1 Like

You have to keep a reference to the BlobAssetStore that you create in line 28.
Otherwise, the native collections inside it will start complaining when the asset store gets out of scope.

2 Likes

I don’t. I checked project for NativeArray, never happens, not once in my entire project. There are references in the package, but not in the Asset folder.

That solved it perfectly. I created a field, and then created new instance before using it. But why? Is this a bug or am I just stupid? Shouldn’t you keep the reference regardless?

Edit: Nevermind, now when I exit play mode I get the same three messages. What to do now?

1 Like

You have to dispose of the asset store somewhere, that blob asset store should be coupled to the lifetime of the world tho.

The easier way is to just grab the BlobAssetStore which the ConvertToEntitySystem uses. You can get a reference to it by calling defaultWorld.GetExistingSystem<ConvertToEntitySystem>().BlobAssetStore

1 Like