I use a hybrid approach where gameobjects (used for animations and game controls) follow relative entities on LateUpdate(). Entity destruction is done via command buffers in Systems. In the monobehaviour of follower gameobject, I check for followed entity’s destruction with if (_entityManager.Exists(EntityToFollow)):
public class FollowEntity : MonoBehaviour
{
public Entity EntityToFollow;
private EntityManager _entityManager;
void Start()
{
_entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
}
void LateUpdate()
{
if (_entityManager.Exists(EntityToFollow))
{
// get some component X of the entity and sync this
// gameobject with it, HERE SOMETIMES FAILS NOT FINDING THE COMPONENT
}
else
{
// do the stuff when an entity dies
}
}
Example of entity destruction in SystemBase:
EntityCommandBuffer.ParallelWriter _entityCommandBuffer = _commandBufferSystem.CreateCommandBuffer().AsParallelWriter(); //BeginFixedStepSimulationEntityCommandBufferSystem
Dependency = Entities
.WithBurst()
.WithAll<EnemyTag>()
.WithReadOnly(_world)
.ForEach((
int entityInQueryIndex,
Entity e,
ref LifeData life,
in JoinDistanceData joinDist,
in LocalToWorld ltw,
in IsFollowingData isFollowing
) =>
{
...
_entityCommandBuffer.DestroyEntity(entityInQueryIndex, e);
...
})
.ScheduleParallel(Dependency);
_commandBufferSystem.AddJobHandleForProducer(Dependency);
This approach works for some systems, not for other systems or when I destroy entities while changing scene. When it fails, it bypasses the Exists test and throws me the “A component with type:Unity.Transforms.Translation has not been added to the entity” exception, obviously as the entity has been destroyed but still trying to access it. It looks apparently random to me when this test is done and when it is bypassed, so I even hypothesized it could be branch prediction i.e. it does the test later and always executes the code, eventually rolling back whether the test is negative, and in this code it gets components of an entity that does not exists. Anyway, the entityManager.Exists test would be pretty useless if branch prediction may occur, I guess…
If you have any hints on this, it would help a lot! Thank you
