Overlay two materials on an Entity RenderMesh

Hello! I am currently porting a terrain system to ECS and am having difficulty replicating GameObject MeshRenderer functionality inside of an ECS RenderMesh

The main issue is that MeshRenderer has a .materials array whereas RenderMesh seems to only support a single list. Background below – to clarify, I am attempting to overlay two materials on the same mesh with transparency. I am not trying to apply a different material to each of multiple submeshes.

Background: The terrain system I have consists of a few dozen 3D tile prefabs – e.g. curved segments of terrain, not cubes. At runtime, I read in a terrain file (from a server, can’t be assembled statically) containing a grid of tile types. For each tile, I select corresponding mesh and apply a single terrain material (UV mapped to a sprite sheet). Later on, I use mesh.CombineMeshes to process the grid of terrain tiles into 16x16 chunks.

So far so good. The issue arises when I need to apply a second material to the terrain. I have a feature that allows users to toggle various environment overlays. These use a custom shader to render another texture on top of the terrain with transparency. I’ve attached an image below. I have no idea how to replicate this effect using an Entity instead of a GameObject to represent each chunk, as there seems to be no way to apply multiple materials.

If you look at how the conversion system does it, it simply creates 1 entity per material with a shared parent. Pretty much what you should do as well.

1 Like

Thanks for your reply! Mind elaborating a bit? If I have two entities each with their own RenderMesh (material + mesh), won’t I just get two overlapping meshes with different materials, render glitching which is on top depending on numerical precision? How do I parent two materials to the same mesh?

Generally this is what the subMesh field is for.
Your first material would be 0, your second would be 1.

1 Like

Thanks – with some fiddling, this worked. I didn’t end up figuring out how to parent entities, but the texture overlays work perfectly

      Entity terrain = this.entityManager.CreateEntity(this.chunkArchetype);
      this.entityManager.AddComponentData(terrain, new Translation       { Value = translation} );
      this.entityManager.AddComponentData(terrain, new RenderBounds      { Value = mesh.bounds.ToAABB()} );
      this.entityManager.AddSharedComponentData(terrain, new RenderMesh  {mesh = mesh, material = mat, subMesh=0} );

      Entity overlays = this.entityManager.CreateEntity(this.chunkArchetype);
      this.entityManager.AddComponentData(overlays, new Translation      { Value = translation} );
      this.entityManager.AddComponentData(overlays, new RenderBounds     { Value = mesh.bounds.ToAABB()} );
      this.entityManager.AddSharedComponentData(overlays, new RenderMesh {mesh = mesh, material = this.overlayMatl, subMesh=1} );