Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Access static NativeList/NativeParallelHashMap in Entities.ForEach results in error error DC0012

Discussion in 'Entity Component System' started by slushieboy99, Aug 19, 2023.

  1. slushieboy99

    slushieboy99

    Joined:
    Aug 29, 2014
    Posts:
    74
    Hi all,
    I'm trying to access static hashmaps and lists inside an Entities.ForEach(), I have the following code:

    Code (CSharp):
    1. NativeParallelHashMap<FixedString64Bytes, Entity> armorMap = CharacterCustomizationHandler.CustomizationAndArmorMap;
    2.         NativeParallelMultiHashMap<FixedString64Bytes, FixedString64Bytes> armorOverrideMap = CharacterCustomizationHandler.ArmorOverrideMap;
    3.         NativeParallelHashMap<FixedString64Bytes, int> slotBaseIndexMap = CharacterCustomizationHandler.SlotBaseIndexMap;
    4.         NativeParallelHashMap<FixedString64Bytes, int> slotArmorIndexMap = CharacterCustomizationHandler.SlotArmorIndexMap;
    5.      
    6.         Entities.WithReadOnly(armorMap).WithReadOnly(armorOverrideMap).WithReadOnly(slotBaseIndexMap).WithReadOnly(slotArmorIndexMap)
    7.             .ForEach((Entity e, ref DynamicBuffer<ArmorCustomizationBufferElement> armorBuffer, ref DynamicBuffer<BaseCustomizationBufferElement> baseBuffer,  in NeedsArmorUpdateComponent armorUpdateComponent, in CharacterTypeComponent characterTypeTag) => {}).Schedule()
    However, it's throwing me the error,
    error DC0012: Entities.WithReadOnly is called with an invalid argument armorMap. You can only use Entities.WithReadOnly on local variables that are captured inside the lambda. Please assign the field to a local variable and use that instead.

    How can I make this work? I'd rather not copy these lists every frame, they may get rather large.
     
  2. Spy-Master

    Spy-Master

    Joined:
    Aug 4, 2022
    Posts:
    274
    I would highly recommend that you begin using IJobEntity. You'll probably see your assemblies compile more quickly when EFE source generation doesn't need to run, as that is pretty expensive. You can pass in native containers like that parallel hash map into the job and schedule it pretty easily. For now, the error message is pretty descriptive. If that code you posted is the full code and there isn't anything inside the EFE lambda, you won't get a proper compilation result unless you actually reference the local variable inside the lambda itself, so you need to have some code in there using the variable so things can be set up correctly by the source generator.
     
    slushieboy99 and xVergilx like this.
  3. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,292
    If you don't use a variable - don't add it to .WithReadOnly(...).
     
    slushieboy99 likes this.