- Home /
Doing a double loop in a job in ecs with Job Entites.forech
I am trying to do a double forech loop in Unity ECS within a JOB, a gravitaional like system. I have done it already succesfully with Unity 2018 with a IJOBParalleForEach, but the code didnt work with Unity 2019 so I tried it now with the new Job Entites.forech and it doesnt work either, I really have no idea why I get the error: error DC0001: Entities.ForEach Lambda expression uses field 'physicsMasses'. Either assign the field to a local outside of the lambda expression and use that instead, or use .WithoutBurst() and .Run().
using System.Collections; using System.Collections.Generic; using UnityEngine; using Unity.Entities; using Unity.Jobs; using Unity.Transforms; using Unity.Mathematics; using Unity.Physics; using Unity.Collections;
public class SwarmSystem : JobComponentSystem {
public float time;
public float gravK = 6.674f;
EntityManager entityManager;
[DeallocateOnJobCompletion] NativeArray<Translation> translations;
[DeallocateOnJobCompletion] NativeArray<PhysicsMass> physicsMasses;
protected override void OnCreate()
{
var v = GameObject.FindObjectOfType<MyGameManager>();
entityManager = v.entityManager;
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
EntityQuery q = GetEntityQuery(ComponentType.ReadOnly<IsPartOfSwarmTag>(), ComponentType.ReadOnly<Translation>(), ComponentType.ReadOnly<PhysicsMass>());
time = Time.DeltaTime;
translations = q.ToComponentDataArray<Translation>(Allocator.TempJob);
physicsMasses = q.ToComponentDataArray<PhysicsMass>(Allocator.TempJob);
var job = Entities.WithAll<IsPartOfSwarmTag>().ForEach((Entity e, ref ForceData f, in PhysicsMass pm, in Translation t ) => {
for(int i = 0; i< translations.Length; i++)
{
float k = physicsMasses[i].InverseMass * pm.InverseMass * gravK;
float3 vec = t.Value - translations[i].Value;
float length = math.length(vec);
float potenz = math.pow(length, 3);
f.Value += (k / potenz) * vec;
}
}).Schedule(inputDeps);
return job;
} }
ForceData is just a float3 IComponentData
Answer by andrew-lukasik · May 29, 2020 at 08:51 PM
It wants you to change it to a local variable
var physicsMasses = q.ToComponentDataArray<PhysicsMass>(Allocator.TempJob);
or make an local alias variable and use it in your job
var localPhysicsMasses = physicsMasses;//use localPhysicsMasses from now on
NOTE: if you make your system inherit from SystemBase you will be able to use Job
semantics (imo more fitting here)
thanks for the answer! (old post but I totally missed to reply)
Your answer
![](https://koobas.hobune.stream/wayback/20220612224721im_/https://answers.unity.com/themes/thub/images/avi.jpg)