I have poor performancence in very simple system that spawns cubes (ecs prefabs) from a spawner. I am using authoring workflow. Longer it works slower it gets. I do not understand why CommandBuffer is getting slower and slower. spawning rate does not change.
using System;
using Unity.Entities;
using Unity.Mathematics;
[Serializable]
public struct Spawner : IComponentData
{
public Entity prefab;
public float3 size;
public float spawnRate;
public float time;
}
using System.Collections.Generic;
using Unity.Entities;
using UnityEngine;
[DisallowMultipleComponent]
[RequiresEntityConversion]
public class SpawnerAuthoring : MonoBehaviour, IConvertGameObjectToEntity, IDeclareReferencedPrefabs
{
public GameObject prefab;
public Vector3 size;
public float spawnRate;
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
dstManager.AddComponent(entity, ComponentType.ReadWrite<Spawner>());
dstManager.SetComponentData(entity, new Spawner()
{
prefab = conversionSystem.GetPrimaryEntity(prefab),
spawnRate = spawnRate,
time = 1f / spawnRate,
size = size
});
}
public void DeclareReferencedPrefabs(List<GameObject> referencedPrefabs)
{
referencedPrefabs.Add(prefab);
}
public void OnDrawGizmosSelected()
{
Gizmos.DrawCube(transform.position, size);
}
}
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
using Random = Unity.Mathematics.Random;
public class Spawner2System : JobComponentSystem
{
private Random rand;
private BeginSimulationEntityCommandBufferSystem barrier;
protected override void OnCreate()
{
rand = new Random(42);
barrier = World.Active.GetOrCreateSystem<BeginSimulationEntityCommandBufferSystem>();
}
struct Spawner2SystemJob : IJobForEachWithEntity<Spawner>
{
public Random rand;
public EntityCommandBuffer.Concurrent PostUpdateCommands;
public float deltaTime;
public void Execute(Entity e, int index, ref Spawner spawner)
{
spawner.time -= deltaTime;
if (spawner.time <= 0)
{
var abs = math.abs(spawner.time);
int count = (int) (abs / (1 / spawner.spawnRate) + 1);
var entity = PostUpdateCommands.Instantiate(index, spawner.prefab);
for (int i = 0; i < count; i++)
{
PostUpdateCommands.SetComponent(index, entity, new Translation()
{
Value = rand.NextFloat3(-spawner.size, spawner.size)
});
}
spawner.time += 1f / spawner.spawnRate;
}
}
}
protected override JobHandle OnUpdate(JobHandle inputDependencies)
{
var job = new Spawner2SystemJob()
{
deltaTime = Time.deltaTime,
PostUpdateCommands = barrier.CreateCommandBuffer().ToConcurrent(),
rand = rand
};
var handle = job.Schedule(this, inputDependencies);
barrier.AddJobHandleForProducer(handle);
return handle;
}
}
