Version: 2022.3
言語: 日本語
C# スクリプトでのシェーダーキーワードの使用
シェーダーバリアントのストリッピング

マテリアルインスペクターでのシェーダーキーワードの使用

Unity エディターでは、マテリアルインスペクターでマテリアルを表示し、そのローカルシェーダーキーワードを有効にしたり無効にしたりすることができます。これは 2 つの理由で役に立ちます。

  • アーティストは、コードを使わずに、マテリアルごとに異なるキーワードを簡単に設定することができます。
  • [KeywordEnum] MaterialPropertyDrawer を使ってキーワードを有効にすると、Unity は自動的にセット内の他のキーワードを無効にします。これにより、常に 1 つのセットから 1 つのキーワードが有効になります。

他のシェーダー設定やデータと同様に、シェーダーキーワードは、シェーダーソースファイル内で マテリアルプロパティ として宣言されている場合にのみ、マテリアルインスペクターで使用できます。

Shader Graph で作成されたシェーダーの場合、キーワードはデフォルトでマテリアルのプロパティです。つまり、これらの設定は自動的にマテリアルインスペクターで使用可能です。これを変更するには、ブラックボード を開いて Exposed プロパティを変更します。

For hand-coded shaders, you must ensure that your ShaderLab code defines a material property that represents the keyword set. The material property must have a type of Float, and must use the [Toggle], [ToggleOff], or [KeywordEnum] MaterialPropertyDrawer attribute to expose it correctly to the Inspector.

Shader "Custom/ApplyEffectIfKeywordIsOn"
{
    Properties
    {
        // Display a toggle in the Material's Inspector window
            [Toggle] _Keyword ("Keyword", Float) = 0.0
    }

    SubShader
    {
        Pass
        {
            #pragma shader_feature _Keyword

            fixed4 frag(v2f i) : SV_Target
            {
                    #if _Keyword
                        // If _Keyword is on at build time, Unity creates a shader variant that uses the following code
                        ApplyEffect();
                    #endif
            
            // rest of shader code...
            }
        }
    }
}

For more information and examples, see the documentation for the MaterialPropertyDrawer API.

C# スクリプトでのシェーダーキーワードの使用
シェーダーバリアントのストリッピング