Search Unity

Create entities in job?

Discussion in 'Entity Component System' started by JamesWjRose, Feb 21, 2020.

  1. JamesWjRose

    JamesWjRose

    Joined:
    Apr 13, 2017
    Posts:
    687
    I am attempting to create some entities within a job, long story, just go with me on this:

    So I have a native array filled with some entities that I create in a mono behavior (a small collection of Autos)

    Within the job I have:
    Code (CSharp):
    1.  
    2. var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
    3. Entity prefab = autoPrototypes[randomValue];
    4. var autoEntity = entityManager.Instantiate(prefab);
    5.  
    But on the third line an exception is thrown:
    The native container may not be deallocated on a job.
    Use [DeallocateOnJobCompletionAttribute] to deallocate a native container safely on job completion.

    So... what dumbass thing am I doing?
     
  2. thelebaron

    thelebaron

    Joined:
    Jun 2, 2013
    Posts:
    857
    Well first of all you cant use EntityManager inside of a job, you need to use EntityCommandBuffers(detailed here https://docs.unity3d.com/Packages/com.unity.entities@0.6/manual/entity_command_buffer.html )

    For the error, just add that attribute next to the nativearray inside your job code

    Code (CSharp):
    1. struct MyJob : IJob{
    2. [DeallocateOnJobCompletion] public NativeArray<Translations> TranslationsArray;
    3. public void Execute()
    4.     {
    5. //stuff
    6.     }
    7. }
     
    JamesWjRose likes this.
  3. JamesWjRose

    JamesWjRose

    Joined:
    Apr 13, 2017
    Posts:
    687
    Thank you, I will look to Command Buffer.

    Have a great weekend
     
  4. BackgroundMover

    BackgroundMover

    Joined:
    May 9, 2015
    Posts:
    224
    Personally I struggle with the job syntax and like the Entities.ForEach() way a lot more. In a SystemBase.