Home > Back-end >  Material property change via code doesn't show
Material property change via code doesn't show

Time:12-28

I'm using Unity 2020.3.3f1 (HDRP) I have a prefab (cube) which has a emissive material on it. After pressing the mouse button, I want it to increase its Emission intensity by 10.

Problem that I encountered: The Inspector shows me that the Intensity is infact changing but the Game does not represent these changes (this means it's not getting "brighter" even though the material property says it does).

Now when I increase the amount via the Inspector manually, just by 0.1 even, all of the sudden the changes are now visible.

I think I tried everything now without luck...

How the code looks like in a nutshell:

public Material cubeMaterial;
private float intensity = 10;

if("mouseClick"){
intensity  = 100;
cubeMaterial.setFloat("_EmissiveIntensity", intensity);
}

CodePudding user response:

If you intend to modify only this gameObject, I recommand you to use MaterialPropertyBlock to modify a property of you material.

If you don't, a new material will be created behind the scene and can lead to memory problems.

To do this, get a reference to the gameObject's renderer, get its property blcok, mofy it and reassign the modified property block.

You can learn more on this documentation

Hope that helped ;)

CodePudding user response:

I suppose you are using the default HDRP/Lit shader for your material. If that's so, you can access your cube emission intensity via "_EmissiveColor" shader keyword like this:

cubeMaterial.GetColor("_EmissiveColor");

which returns a float value.

And you can modify it the similar way:

cubeMaterial.SetColor("_EmissiveColor", startingEmission 10);

In general, when working with HDRP material shaders it's always safe to look up the shader keywords, you can do it via navigating to your material in the inspector, clicking the kogwheel and selecting edit shader, which opens the .shader file.

  • Related