Unity3d shader Shader's Boolean switch variable [Toggle] component C# script control is invalid problem solution

question

The effect shader of a model is called up in the scene effect, and the program needs to dynamically modify an attribute of the shader. The attributes are as follows:

[Toggle(_USELINE_ON)] _UseLine("Use Line", Float) = 0

According to my previous understanding, it should be no problem if I directly modify the value of Float to 1 or 0:

//关闭
 AniMat2.SetFloat("_UseLine", 0);
 
//打开
 AniMat2.SetFloat("_UseLine", 1);

However, it didn't work, and after searching the web page for a long time, no results were found. Finally, a breakthrough was found in the code generated by the shader.

Solution

See a lot of similar snippets in shader code:

#ifdef _USELINE_ON
...
#else
...
#endif

[Toggle(_USELINE_ON)] is associated with _USELINE_ON
This is a macro definition, then I can dynamically modify the macro definition to complete the control

The way to do this is this = dynamic modification macro definition =
disable the local shader keyword for this material. Material.DisableKeyword method:

insert image description here
Enables the local shader keyword for this material. Material.EnableKeyword method:

insert image description here
In this way, you can control the Toggle effect of the shader

//关闭
  AniMat2.DisableKeyword("_USELINE_ON");
//打开
  AniMat2.EnableKeyword("_USELINE_ON");

Invalid after packing

The problem that this function is invalid after packaging, I solved it through https://www.jianshu.com/p/32f6e8a217d6 .

I solved it by modifying Shader - multi_compile by method 3.

Guess you like

Origin blog.csdn.net/weixin_43149049/article/details/127352662