Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved Best way to change material of an entity in ISystem run time?

Discussion in 'Entity Component System' started by MatanYamin, May 14, 2023.

  1. MatanYamin

    MatanYamin

    Joined:
    Feb 2, 2022
    Posts:
    109
    Hey everyone,

    In my game I need to change an entity's material when the player get close to it.

    I have thousands of entities spreading around, so I must use ISystem with Burst for best performance.

    The issue is - changing shared components like "RenderMeshArray" in ISystem is impossible (hopefully I'm wrong).

    So what is the best approach to achieve my goal?

    I thought maybe use both ISystem and SystemBase: ISystem to check the distance repeatedly to the player, and SystemBase to change the material of the entity in the main thread when the entity is close enough.

    Does someone have a better approach? Or this is wrong and I'm missing something?
    I will be more than happy to hear!

    Thanks!
     
  2. SillyConesValley

    SillyConesValley

    Joined:
    May 13, 2023
    Posts:
    6
    Last edited: May 14, 2023
    MatanYamin likes this.
  3. MatanYamin

    MatanYamin

    Joined:
    Feb 2, 2022
    Posts:
    109
  4. Tsoj88

    Tsoj88

    Joined:
    Nov 27, 2020
    Posts:
    2
    If you want to change material and not the material property, you can do this with MaterialMeshInfo. You'll need to register the material to the EntitiesGraphicsSystem and get its BatchMaterialID. There is an example of how to register in the EntityComponentSystemSamples\URPSamples\Assets\SampleScene\MaterialMeshChange. After this you can use the BatchMaterialID in a burst job to change the entity's material by updating its MaterialMeshInfo component. You'll probably want to use something like a NativeHashMap to store the BatchMaterialID with a key.
     
    Last edited: May 15, 2023
    MatanYamin likes this.
  5. MatanYamin

    MatanYamin

    Joined:
    Feb 2, 2022
    Posts:
    109
    Man, you don't know how much you helped me. After some coding and debugging I finally got it to work, with a lot of help to your answer. Thanks again!!
     
    Tsoj88 likes this.