using UnityEngine;
using Unity.Mathematics;
using Unity.Entities;
using Unity.Transforms;
using Unity.Rendering;
public class RenderEntityTest : MonoBehaviour
{
EntityManager manager;
EntityArchetype particleArch;
public Mesh mesh;
public Material material;
RenderMesh rm;
RenderBounds rb;
void Start()
{
manager = World.DefaultGameObjectInjectionWorld.EntityManager;
particleArch = manager.CreateArchetype(
typeof(Translation),
typeof(LocalToWorld),
typeof(RenderBounds),
typeof(RenderMesh));
rm = new RenderMesh()
{
castShadows = UnityEngine.Rendering.ShadowCastingMode.On,
receiveShadows = true,
mesh = mesh,
material = material,
};
rb = new RenderBounds() { Value = mesh.bounds.ToAABB() };
// This will create 100 entities in the same chunk:
//SpawnABunch(100);
}
void Update()
{
// This will create a new chunk for each new entity:
SpawnABunch(1);
}
void SpawnABunch(int count)
{
for (int i = 0; i < count; i++)
{
Spawn(UnityEngine.Random.insideUnitSphere * 10);
}
}
void Spawn(Vector3 pos)
{
Entity e = manager.CreateEntity(particleArch);
manager.SetComponentData(e, new Translation { Value = pos });
manager.SetSharedComponentData(e, rm);
manager.SetComponentData(e, rb);
}
}
I am pretty sure this is a problem with the AddWorldAndChunkRenderBounds system, because if you don’t add one of the necessary components, for example MeshBounds, which prevents that system from kicking in, the entities are added into existing chunks as they should be.
I’m using the latest 0.3.4-preview.24 in Unity 2019.3.3f1
And yes, I need to create RenderBounds manually as is mentioned in the post. So, apparently this version should’ve had the fragmentation issue fixed, but it doesn’t?
If you use prefabs, the issue is solved. If you don’t use prefabs and instead build entity from scratch, then you need to add a couple of chunk components manually to solve the issue. I believe you need at least to add ChunkWorldRenderBounds. You could check in entity debugger which chunk components exist in the entity and add those yourself.
Also it’s worth noting that adding all components manually causes several structural changes, and is thus significantly slower than instantiating a prefab which has all components added beforehand during conversion. Prefabs are the fast path for instantiation and result in zero fragmentation too.
We will add a test scene to hybrid.renderer sample projects to show how to build entity from scratch in code in a way that doesn’t cause fragmentation. I would however still recommend instantiating prefabs as that is faster.