unity-dotsunity-ecs

How to change material color of a single entity in SystemBase’s OnUpdate among a lot of similar objects?


I use Unity for a long time, but I’m new to ECS.

I have created a SystemBase to change the color of some entities spawned but not all of them. I want to highlight a sub set of my entities.

I created this SystemBase. It changes the color, but of all of entities that shares the same material. Is there a way to create a new temporary material just for a single entity and reassign to it in order to change just that color?

[UpdateAfter(typeof(CityStageSpawnSystem))]
public partial class ApplyColorSystem : SystemBase
{
    protected override void OnCreate()
    {
    }

    protected override void OnUpdate()
    {
        Entities.ForEach((ref Entity entity, in ChangeColorComponent colorComponent, in RenderMeshArray renderMeshArray, in MaterialMeshInfo materialMeshInfo) =>
        {
            if(colorComponent.changeIt) {
                var material = renderMeshArray.GetMaterial(materialMeshInfo);
                material.color = new UnityEngine.Color(colorComponent.NewColor.x, colorComponent.NewColor.y, colorComponent.NewColor.z, colorComponent.NewColor.w);
            }
        })
        .WithoutBurst().Run();
    }
}

I already tried a lot of stuff, creating more than one ComponentData instead of that one carrying the color, reviewing my algorithm, etc. etc. The whole point is that renderMeshArray, materialMeshInfo and material are shared among all entities of the same kind. In simple UnityEngine I can do this. Is there a way to overcome this in ECS?


Solution

  • I got overcome this issue in that post I sent to UnityForum:

    https://discussions.unity.com/t/unityecs-how-to-change-material-color-of-a-single-entity-in-systembases-onupdate-among-a-lot-of-similar-objects/1500568

    Basically, you can't use that structs if you want to change a single material of a single entity. Instead, you have to use MaterialOverride. The process starts in Authoring, still in Unity Editor. Take a look at the answer of "DreamingImLatios" and mine too, that comes after it.