Hello everyone, I’m pretty new to Unity ECS, and I’m currently struggling to understand how I can apply it to my existing code.
For my project, I’m using a library to handle a large amount of bullets (I would like to handle 5000 of them at the same time). This library give me a list of bullet elements with a position, a rotation, a scale and a color.
Until now, I was using the Unity particle system (Shuriken) to display these bullets, doing something like that:
public void Update()
{
var bulletParticles = new ParticleSystem.Particle[_bullets.Count];
_particleSystem.GetParticles(bulletParticles);
for (int i = 0; i < bulletParticles.Length; i++)
{
bulletParticles[i].position = _bullets[i].Position;
bulletParticles[i].rotation = _bullets[i].Rotation;
bulletParticles[i].startColor = _bullets[i].Color;
bulletParticles[i].startSize = _bullets[i].Scale;
}
_particleSystem.SetParticles(bulletParticles, bulletParticles.Length);
}
But the particle system is not really done for that, so I would like to switch to the new ECS to have a better control.
I started doing a simple test like that:
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
public static void Initialize()
{
_entityManager = World.Active.GetOrCreateManager<EntityManager>();
}
private static void SpawnBullet(int index)
{
var entity = _entityManager.CreateEntity(
ComponentType.Create<Position>()
ComponentType.Create<TransformMatrix>()
);
_entityManager.AddSharedComponentData(entity, _renderer);
}
So with this I can create entity with a simple Position component. Then, I create a system to move them according to the bullets position:
public class EntityMovementSystem : JobComponentSystem
{
public struct Data
{
public readonly int Length;
public ComponentDataArray<Position> Position;
}
[Inject] private Data data;
[Unity.Burst.BurstCompile]
struct PositionJob : IJobProcessComponentData<Position>
{
public void Execute(ref Position position)
{
// How can I know this Position component correspond to the proper bullet?
position.Value = new float3(
BulletManager.Bullets[i].Position.x,
BulletManager.Bullets[i].Position.y,
0f
);
}
}
protected override JobHandle OnUpdate(JobHandle inputDeps)
{
var positionJob = new PositionJob();
return positionJob.Schedule(this, 64, inputDeps);
}
}
And here is my problem. When the Execute method is called, how can I have an index to make sure the position I update corresponding to the same bullet from my collection?
Is this the correct way to do what I want?
Thank a lot for your answer in advance!