This is my first time exploring ECS/DOTS. I am NOT a programmer so I not too sure on this stuff.
Can anyone comment on my code? It seems to run and not log any errors. But I am not sure if I am laying out everything efficiently. Is there any improvements I should make?
I couldn’t find any examples/docs on good practices when it comes to using burst with a Entities.ForEach job as appose to IJobChuck. Is it okay to use burst with Entities.ForEach? I will eventually learn how to use IJobChuck but for learning purposes I want to do it later once I am more comfortable with this new way to coding.
Another question is about public Entity prefab; in SpawnerData.cs. Is Entity considered as a value type or reference type? Is it considered blittable?
Thanks for your help!
SpawnerData.cs
public struct SpawnerData : IComponentData
{
public Entity prefab;
public int count;
public float rate; // Spawn rate
public float delay; // Time delay before the first spawn
public float next; // Time until the next spawn
}
SpawnerAuthoring.cs
public class SpawnerAuthoring : MonoBehaviour, IConvertGameObjectToEntity
{
public GameObject prefab;
public int count = 10;
public float rate = 1f;
public float delay = 2f;
private float next = 0f;
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
SpawnerData data = new SpawnerData();
var conversionSetting = GameObjectConversionSettings.FromWorld(dstManager.World, conversionSystem.BlobAssetStore);
data.prefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(prefab, conversionSetting);
data.count = count;
data.rate = rate;
data.delay = delay;
if (delay == 0f)
data.next = 0f;
else
data.next = delay;
dstManager.AddComponentData<SpawnerData>(entity, data);
}
}
SpawnerSystem.cs
public class SpawnerSystem : SystemBase
{
private EndSimulationEntityCommandBufferSystem commandBufferSystem;
protected override void OnCreate() { commandBufferSystem = World.GetOrCreateSystem<EndSimulationEntityCommandBufferSystem>(); }
protected override void OnUpdate()
{
var dT = Time.DeltaTime;
var commandBuffer = commandBufferSystem.CreateCommandBuffer().ToConcurrent();
Entities.ForEach((Entity entity, int entityInQueryIndex, ref SpawnerData data) =>
{
// Check if it is time to spawn
if (data.next <= 0f)
{
commandBuffer.Instantiate(entityInQueryIndex, data.prefab); // Spawn a prefab entity
data.count--; // Reduce the spawn count
// Check if spawn count has reached 0
if (data.count == 0)
{
commandBuffer.DestroyEntity(entityInQueryIndex, data.prefab); // Destroy the reference entity
commandBuffer.DestroyEntity(entityInQueryIndex, entity); // Destroy this entity
}
else
data.next = data.rate; // Reset the spawn timer
}
else
data.next -= dT; // Reduce the time until next spawn
}).WithBurst().ScheduleParallel();
commandBufferSystem.AddJobHandleForProducer(Dependency);
}
}