For some reason when I update the lifetime of one of my particles inside a BurstJob it also updates and in this case kills all other particles that should stay alive.
Code:
[BurstCompile(FloatPrecision.Standard, FloatMode.Fast, CompileSynchronously = true)]
public struct UpdateParticlesJob : IJobParticleSystemParallelForBatch
{
public float deltaTime;
[ReadOnly] public NativeArray<float3> rotations;
[ReadOnly] public NativeArray<float> speeds;
[ReadOnly] public NativeArray<float> ranges;
public NativeArray<float> distancesTraveled;
public void Execute(ParticleSystemJobData particles, int startIndex, int count)
{
NativeArray<float> positionsX = particles.positions.x;
NativeArray<float> positionsZ = particles.positions.z;
NativeArray<float> lifetimes = particles.aliveTimePercent;
int endIndex = Mathf.Clamp(startIndex + count, 0, particles.count);
for (int i = startIndex; i < endIndex; i++)
{
float3 movement = rotations[i] * speeds[i] * deltaTime;
positionsX[i] += movement.x;
positionsZ[i] += movement.z;
distancesTraveled[i] += math.length(movement);
if (distancesTraveled[i] >= ranges[i])
{
lifetimes[i] = 100f; // Kill the particle -- This seems to kill all active particles at once
// See the linked video for the bug in action
}
}
}
}
I also have a video showing the bug:
https://streamable.com/vhl16f
As you can see in the code im setting the lifetime of a single particle to 100%(as per documentation), but as shown in the video its actually killing all the other active particles aswell…
Update:
{
var updateParticlesJob = new UpdateParticlesJob
{
deltaTime = InputHandler.Instance.TickDelta,
rotations = particleRotations,
speeds = particleSpeeds,
ranges = particleRanges,
distancesTraveled = distancesTraveled // this is probably why
};
JobHandle jobHandle = updateParticlesJob.ScheduleBatch(_system, 1);
jobHandle.Complete();
}
So as im updating distancesTravelled its OK, but as I remove a particle from the system it keeps that TravalledDistance in the wrong index because the particle no longer exists, so this travveledDistance value is now associated with another particle that does still exist, then this one gets deleted because it thinks its reached it range, and this goes on untill all particles are killed due to the index getting swapped.
So the solution is, when I remove a particle from the system I also need to reset the distanceTravveled to the next particles distanceTravelled. So if index 1 becomes index 0 since we deleted the particle at index 0 then we need to set travelledDistance from index 1 to index 0 and we need to set distanceTravelled from index 2 to index 1, basically shifting everything back, which is a huge mess, how can I do this in a better way?