I'm working on a small DOTS project to get the hang of it.
I'm trying to spawn X entities at the start, and each will move randomly across the screen. However, I don't want a singleton for the random generator, as it forces monothreaded behaviors. Instead, I want each entities to have their own Random component to which they can write.
Here's how I author my random:
public class RandomBaker : Baker<RandomAuthor>
{
public override void Bake(RandomAuthor authoring)
{
AddComponent(new RandomGen()
{
Random = Random.CreateFromIndex((uint) GetEntity(authoring).Index)
});
}
}
Which works great !! As long as I place the Entity in the editor. When I try to spawn my X entities, things go wrong. They all get the same seed. I am under the impression, that when spawning entities from a prefab, the authoring is only done on the prefab, making the instances exact copies of the prefab.
Here's the code that spawns the entities:
var ecb = new EntityCommandBuffer(Allocator.Temp);
for (uint i = 0; i < spawner.NumberOfSpawn; i++)
{
var e = ecb.Instantiate(spawner.Prefab);
UniformScaleTransform trans = new UniformScaleTransform()
{
Position = spawner.GetRandomPos(),
Rotation = Quaternion.identity,
Scale = spawner.PrefabScale,
};
ecb.SetComponent(e, new LocalToWorldTransform() { Value = trans });
}
ecb.Playback(state.EntityManager);
}
As a way to try and fix my issue, I tried adding:
ecb.SetComponent(e, new RandomGen(){ Random = Random.CreateFromIndex((uint)e.Index)));
but it sent me an error saying that the index was equal to uint.MaxValue (??) so I'm not sure that even at that points it knows the future entity's index.
What's the proper way to approach this ?
