I was playing around with the new entity component system and I came across a problem I was not able to solve.
I try to make an entity follow another entity. I want to do it in a job and **not** on the main thread.
I already wrote some code in order to accomplish that:
FollowEntityComponent.cs
using Unity.Entities;
using Unity.Mathematics;
public struct FollowEntityComponent : IComponentData
{
public Entity entityToFollow;
public float3 offset;
}
FollowEntitySystem.cs
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using Unity.Jobs;
using Unity.Burst;
using Unity.Collections;
public class FollowEntitySystem : JobComponentSystem
{
struct FollowEntityJob : IJobForEach
{
[ReadOnly] public ComponentDataFromEntity translationComponentFromEntityToFollow;
public void Execute(ref Translation translationComponent, ref FollowEntityComponent followEntityComponent)
{
if (!translationComponentFromEntityToFollow.Exists(followEntityComponent.entityToFollow))
{
return;
}
float3 entityToFollowPosition = translationComponentFromEntityToFollow[followEntityComponent.entityToFollow].Value;
translationComponent.Value = entityToFollowPosition + followEntityComponent.offset;
}
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
FollowEntityJob followEntityJob = new FollowEntityJob()
{
translationComponentFromEntityToFollow = GetComponentDataFromEntity(true)
};
return followEntityJob.Schedule(this, inputDeps);
}
}
The code **does** actually compile, however, I get the following error when I hit play:
*InvalidOperationException: The writable NativeArray FollowEntityJob.Iterator is the same NativeArray as FollowEntityJob.Data.translationComponentFromEntityToFollow, two NativeArrays may not be the same (aliasing).*
I already figured out why I am getting this error message. It is because I am having a Translation component in `IJobForEach` and in `[ReadOnly] public ComponentDataFromEntity translationComponentFromEntityToFollow;` this seems to cause the error. (See: https://www.youtube.com/watch?v=KuGRkC6wzMY , minute: 21:53).
However, even when I know the reason I can not figure out a better way of accomplishing what I want to do. I would be very thankful if somebody could provide me a solution to my problem.
↧