I am running Unity 2021.3.1f1
I am updating the surface type of some materials from Transparent to Opaque at runtime using the following code:
material.SetFloat("_SurfaceType", 0f);
Checking the Inspector on the material, the change is actually made, however in the Game View and the Scene view, the material is not actually made opaque.
If I change the surface type in the Inspector manually, the changes are reflected in the Game View and Scene View. Interestingly, after the code ineffectively changes the surface type at runtime, If I make an irrelevant change to some code in Visual Studio and save Visual Studio while the game is still running, then return to the Unity Editor, the materials become opaque.
Is there some way I can force Unity to update the materials with code?
You’d want to use HDMaterial.ValidateMaterial API.
Note that in a build, the shader variants needed to render transparency have to be included. If no material referenced by your scenes include them, they have a high chance to be stripped when building a player, and result in rendering errors.
You can then use ShaderVariantsCollections to force to load them.
The other easy solution is simply to have a material already set to transparent and swap the opaque to this one at runtime.
I am using
using UnityEngine.Rendering.HighDefinition;
and have access to HDCamera;
But HDMaterial does not exist in the current context.
Is HDMaterial only available in Unity 2022?
Hum, yes, this API went public only with Unity 2022 versions.
I updated to Unity 2022.1.20f1. HDMaterial.ValidateMaterial does not have an effect on the materials. They still need to be opened in the editor inspector before they update.